Reputation: 471
I have a JSON string that I can only access and not create. Right now, the format of the JSON looks something like this:
{
"ID": "1",
"value": "{'ID': '1', 'more': {'Key': 'Value', 'Object': {'Akey': 'Avalue'}}}"
}
I want to edit this JSON string to put into another function in a format similar to this:
{
"ID": "1",
"value": "{'ID': '1', 'Key': 'Value', 'Akey': 'Avalue'}"
}
So basically, just remove the More and Object tags from the JSON string and the respective curly brackets. One way this can be done is obviously just use splits and substrings in Java, however, is this the most efficient way? If not, any other ideas on ways I can approach this? I am using Java and the Apache Commons Sling JSON library (no options to change/add Java JSON libraries!)
Thanks for your time!
Upvotes: 0
Views: 785
Reputation: 110
Easy way: We can do it by substring or replace method of string. If need we can use regular expression for more accurate.
Upvotes: 1
Reputation: 3075
Unfortunately, native JSON support was delayed past Java 9.
Either substring & replace as you wrote, for more complicated situations, like removing the whole 'more' object, implement your own parser, for example:
String value = "{'ID': '1', 'more': {'Key': 'Value', 'Object': {'Akey': 'Avalue'}}}";
String delimiter = ", 'more'"; // pay attention to the comma, you can fix it by splitting by comma
int start = value.indexOf(delimiter);
System.out.println("start = " + start);
Stack<Character> stack = new Stack<>();
String substring = value.substring(start + delimiter.length(), value.length());
System.out.println("substring = " + substring);
char[] chars = substring.toCharArray();
int end = 0;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == '{')
stack.push('{');
if (c == '}') {
stack.pop();
if (stack.isEmpty()) {
end = i;
break;
}
}
}
System.out.println("end = " + end);
String substring2 = value.substring(start, start + end + delimiter.length());
System.out.println(substring2);
System.out.println(value.replace(substring2, ""));
by counting parenthesis, output
start = 10
substring = : {'Key': 'Value', 'Object': {'Akey': 'Avalue'}}}
end = 47
, 'more': {'Key': 'Value', 'Object': {'Akey': 'Avalue'}
{'ID': '1'}}
Upvotes: 1