My String input is something like:
{"key1":"value1","key2":"{\"key2_1\":\"123\",\"key2_2\":\"456\",\"key2_3\":\"33333\"}"}
The value fields in the above JSON could contain characters such as "
, \
and so on. For your convience here is the formatted version:
{
"key1": "value1",
"key2": "{\"key2_1\":\"123\",\"key2_2\":\"456\",\"key2_3\":\"33333\"}"
}
I want to use Gson to convert the String into a Foo Object:
class Foo {
private String key1;
private Bar key2;
...
}
class Bar {
private String key2_1;
private String key2_2;
private String key2_3;
...
}
Here's my regular expression:
String regexp = "\\{[\"a-zA-Z-0-9:,\\\\]*\"key2\":\"\\{\\\\\"key2_1\\\\\":\\\\\"[a-zA-Z0-9]*\\\\\",\\\\\"key2_2\\\\\":\\\\\"[a-zA-Z0-9]*\\\\\",\\\\\"key2_3\\\\\":\\\\\"[a-zA-Z0-9]*\\\\\"\\}\"\\}[\"a-zA-Z-0-9:,\\\\]*";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(text);
if(matcher.matches()) {
... // TODO: Replace all "{, \" and }" but How???
}
How could I use this regular expression to replace all "{
, \"
.and "}
into {
, "
, }
without changing the keys and values in JSON?
Finding the sub-string and using String's replace method will be my backup solution.
Again, my ultimate goal is to parse the input String into my Foo object. Is there a better way rather than using regular expression?
Thank you!