Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trailing characters getting parsed in json

Tags:

java

json

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.

like image 666
iec2011007 Avatar asked Nov 09 '22 10:11

iec2011007


1 Answers

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.

like image 92
Serge Ballesta Avatar answered Nov 14 '22 21:11

Serge Ballesta