Reputation: 6289
I have a string created from a JSON object as follows
{
"id" : "112233",
"someElement" : [ {
"map" : {
"123" : [ {..}]
},
"map" : {
"124" :[ {..}]
}
}]
}
I need to convert the above string to the following format.
{
"id" : "112233",
"someElement" : [ {
"123" : {
"element" : [ {..}]
},
"124" : {
"element" :[ {..}]
}
}]
}
I tried to do string substitution as when the substring "map" is found in the string, replace with the ID just beneath it.
String a = jsonString.substring(jsonString.indexOf("map")+16, jsonString.indexOf("map")+19);
String b = jsonString.replace("map", a);
This pattern works for the first occurrence of "map" string. But the same ID value replaces the second "map" string. How do I replace the subsequent occurrences of "map" string with their respective IDs.
Also, is there any better way to do this? Appreciate any feedback.Thanks!
Upvotes: 1
Views: 136
Reputation: 269717
JSON is not a regular language, so trying to make this kind of change with a regular expression will be fragile; syntactically insignificant variations in the input will easily confuse your regular-expression–based solution.
Because this example violates the JSON recommendation for keeping object member names unique, many JSON parsers will have difficulty parsing it, raising an exception or ignoring some members. However, there might be parsers out there that handle it. If not, it's very easy write your own parser for JSON that will handle this input robustly. Then your code won't break when the whitespace changes.
Upvotes: 2