3

Using Java is there an easy way to check whether a given file conforms to json format?

Using gson, the best i can do is:

private final JsonParser parser = new JsonParser();
jsonElement = parser.parse(new FileReader(fileName));

    if (jsonElement.isJsonObject()) {
        return true;
    } else {
        return false;
    }

Any cleaner ideas?

1 Answer 1

12

Gson will throw JsonParseException if the JSON is not parseable. You just have to catch that with JsonParser#parse() in the try.

try {
    new JsonParser().parse(jsonSource);
    // Valid.
} catch (JsonParseException e) {
    // Invalid.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.