2

I was using the following to check if a json file was valid:

JsonParser parser = new JsonParser();   
parser.parse(new String(Files.readAllBytes(Paths.get((filePath.toString())))));

But the json file I am validating has trailing commas like below that it doesn't throw an exception for:

"file":"hello.htm"},]

Since this is the last attribute the comma isn't needed and is causing trouble in other areas of our application. Is there a parser or some way to catch this trailing comma?

2
  • Good option could be removing these commas before validation, look this for more details stackoverflow.com/questions/34344328/… Commented Jun 22, 2016 at 20:04
  • What JsonParser type is this? Commented Jun 22, 2016 at 20:09

2 Answers 2

2

Assuming JsonParser is part of Gson, you're currently out of luck. Gson's parsing currently interprets the trailing comma in a JSON array as a null value. It's wrong and a resolution seems to be planned for Gson 3.

In the meantime, you can use a different parsing library. I suggest Jackson. If you're just validating the JSON, you can use

ObjectMapper mapper = new ObjectMapper();
mapper.readTree(Files.readAllBytes(Paths.get(filePath.toString())));

This will throw an exception, with a message similar to

Unexpected character (']' (code 93)): expected a value

indicating that it expected an actual value after the ,, not the closing array symbol.

Sign up to request clarification or add additional context in comments.

1 Comment

Sadly Gson devs are not willing to fix this(
-1

When iterating the JSONArray, you could ask if the element is null:

for (i in 0 until jsonArray.length()) {
    if (!jsonArray.isNull(i)) {
        // parse here...
    }
}

And then you would be able to avoid the 'org.json.JSONException' exception.

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.