The behavior of the org.json.JSONObject(String) is different from all the other
commonly used open-source JsonParsers including the OJAI, in case of duplicate keys.
JSONObject(String) throws a JsonException if the string has json text with
duplicate keys, where as Gson, Jackson, and OJAI consider overwriting the value.
Repro Snippet:
//create a valid json with duplicate keys in the map
String inputJson = "{\n" +
" \"pid\" : \"123\",\n" +
" \"age\" : 18,\n" +
" \"name\" : \"Snowfire\",\n" +
" \"created_at\" : \"2015-09-08 T 11:30:28\",\n" +
" \"pid\" : \"456\"\n" +
"}";
//OJAI
Document doc = Json.newDocument(inputJson);
System.out.println("Document :" + doc.toString());
//Jackson
ObjectMapper objMapper = new ObjectMapper();
JsonNode actualObj = objMapper.readTree(inputJson);
System.out.println("JackSon :" + actualObj.toString());
//Gson
JsonObject gsonObj = new JsonParser().parse(inputJson).getAsJsonObject();
System.out.println("Gson :" + gsonObj.toString());
//org.json
JSONObject jsonObj = new JSONObject(inputJson);
StdOut:
Document :{"pid":"456","age":18,"name":"Snowfire","created_at":"2015-09-08 T
11:30:28"}
JackSon :{"pid":"456","age":18,"name":"Snowfire","created_at":"2015-09-08 T
11:30:28"}
Gson :{"pid":"456","age":18,"name":"Snowfire","created_at":"2015-09-08 T
11:30:28"}
org.json.JSONException: Duplicate key "pid"
at org.json.JSONObject.putOnce(JSONObject.java:1163)
at org.json.JSONObject.(JSONObject.java:214)
at org.json.JSONObject.(JSONObject.java:321)
The behavior of the org.json.JSONObject(String) is different from all the other
commonly used open-source JsonParsers including the OJAI, in case of duplicate keys.
JSONObject(String) throws a JsonException if the string has json text with
duplicate keys, where as Gson, Jackson, and OJAI consider overwriting the value.
Repro Snippet:
StdOut:
Document :{"pid":"456","age":18,"name":"Snowfire","created_at":"2015-09-08 T
11:30:28"}
JackSon :{"pid":"456","age":18,"name":"Snowfire","created_at":"2015-09-08 T
11:30:28"}
Gson :{"pid":"456","age":18,"name":"Snowfire","created_at":"2015-09-08 T
11:30:28"}
org.json.JSONException: Duplicate key "pid"
at org.json.JSONObject.putOnce(JSONObject.java:1163)
at org.json.JSONObject.(JSONObject.java:214)
at org.json.JSONObject.(JSONObject.java:321)