5
votes

I am trying to check if json is valid and I am experiencing a bizzare behaviour. When I append some characters to a parsable json both jackson and gson are parsing it and they ignore the trailing charaters. I want to check if the json is strictly valid. Please help. I tried a couple of flags in mapper.configure() but I couldn't find the exact setting.

import com.google.gson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

public class JSONUtil {
    public static void main(String[] args) {
        String jsonStr = "{\"outputValueSchemaFormat\": \"\",\"sortByIndexInRecord\": 0,\"sortOrder\":\"descending\"}opdfahf";
        System.out.println(JSONUtil.isValidJson(jsonStr));
    }
    public static boolean isValidJson(String str) {
        try {
             final ObjectMapper mapper  = new ObjectMapper();
             mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
             mapper.readTree(str);
         System.out.println(str);
             new JsonParser().parse(str);

        } catch (Exception e) {
            return false;
        }
            return true;
        }
}

PS: This question is different from this because i have used the same code but it seems that either the library has some bug or some configuration flag is missing. I tried a couple of configuration flag but none seems to work.

2

2 Answers

1
votes

Real world parsers consideres as a feature to accept incorrect JSON provided they can understand it. Among errors that they can easily fix (not all parsers do all, but some can fix some):

  • unquoted identifiers => an identifier should be there with or without quotes
  • single quotes instead of double quotes => trivial to fix
  • trailing characters => the parser can detect the end of the Json string and can ignore whatever comes after
  • ...

TL/DR: a parser is required to accept valid Json, it is simply unspecified what it does with incorrect but understandable data...

IMHO, if you want to strictly validate a Json string, you should build by hand a custom validator controling the syntax given at http://json.org/, or even better the ECMA-404 specification.

0
votes

After some research on the forums i found an interesting link someone who had the same problem. The response from the team was

Yes. This is by design. If you want to catch such problems, you need to construct JsonParser, advance it manually. Existence of multiple root-level values is not considered a validity problem, but in your case, end-of-stream without matching ']' would be caught.

Please refer to the problem here

For solution refer here