Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if file is json, java

Tags:

java

json

gson

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?

like image 331
James Raitsev Avatar asked Apr 08 '26 07:04

James Raitsev


1 Answers

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.
}
like image 54
BalusC Avatar answered Apr 09 '26 22:04

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!