check if file is json, java

匿名 (未验证) 提交于 2018-07-18 20:11:02


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?


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.