I have a String which is in JSON Format
String str = "{\"innerkey1\":\"innervalue1\",
\"innerkey2\":\"innervalue2\",\"innerkey1\":\"innervalue3\"}";
When I am trying to create a object from this string
try {
JSONObject obj = new JSONObject(str);
} catch(Exception e) {
e.printStackTrace();
}
I am getting an error
org.json.JSONException: Duplicate key "innerkey1"
Is there any way we can create the JSONObject by ignoring the last key from the string?
You can use objectMapper to skip this error
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"test\", \"name\":\"new test\"}";
Map<String, Object> map = new HashMap<String, Object>();
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
Now you can easily convert to JSONObject from map
new JSONObject(map);
This is a problem of the JSON specification. Depending on which specification is used, one can interpret whether duplicate keys are permissible at all. In this thread, it has been widely agreed that the definition is that a key must be unique in a JSONObject.
For this reason, you should not try to parse a probably invalid JSON object, but use a valid one.
But I would have a small suggestion for a solution: However you put it into practice, you could use the (multiple occurring) key and assign all the objects stored there as an array to this (now unique) key. So you merge several identical keys and also merge the linked objects into an array. This would at least make the JSON object valid:
{
"a" : "x",
"a" : "y"
}
// becomes
{
"a" : ["x", "y"]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With