Reputation: 12985
I want to convert a string into JSON. JsonObject of java gson. The string is a nested JSON structure in which forward-slash () is added as you can see in name its has \\". ( One \ to escape \ and one \ for ".
How to ignore inner \ and convert into JSON object. I was trying with replaceAll to escapse \\" but did not work as it replaces \" also
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
public static void main(String args[]){
String json = "[{\"key\":\"px\",\"mKeyValues\":[{\"hmKey\":\"qx\",\"value\":\"[{\\\"name\\\":\\\"Test Equipment value\\\",\\\"status\\\":\\\"2\\\"}]\"}]}]";
JsonParser jsonParser = new JsonParser();
json = json.replaceAll("\\\\","");
System.out.println(json);
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
System.out.println(jsonObject);
}
}
Actual Json is
[
{
"key": "px",
"mKeyValues": [
{
"hmKey": "qx",
"value": [
{
"name": "Test Equipment value",
"status": "2"
}
]
}
]
}
]
Upvotes: 1
Views: 4468
Reputation: 134
This will do the trick
json = json.replace("\"[","[").replace("]\"", "]").replace("\\\"", "\"");
Solution with out replace
public static void main(String[] args)
String json = "[{\"key\":\"px\",\"mKeyValues\":[{\"hmKey\":\"qx\",\"value\":\"[{\\\"name\\\":\\\"Test Equipment value\\\",\\\"status\\\":\\\"2\\\"}]\"}]}]";
System.out.println(json);
JsonParser jsonParser = new JsonParser();
JsonArray jsonObject = jsonParser.parse(json).getAsJsonArray();
JsonObject mKeyValues0 = jsonObject.get(0).getAsJsonObject()
.get("mKeyValues").getAsJsonArray()
.get(0).getAsJsonObject();
mKeyValues0.add("value", jsonParser.parse(mKeyValues0.get("value").getAsString() ));
System.out.println(jsonObject);
}
Upvotes: 4
Reputation: 841
You should not parse it as jsonObject since it is a jsonArray get this as jsonArray, something like this
public static void main(String args[]){
String json = "[{\"key\":\"px\",\"mKeyValues\":[{\"hmKey\":\"qx\",\"value\":\"[{\\\"name\\\":\\\"Test Equipment value\\\",\\\"status\\\":\\\"2\\\"}]\"}]}]";
JsonParser jsonParser = new JsonParser();
json = json.replace("\"[","[").replace("]\"", "]").replace("\\\"", "\"");
System.out.println(json);
JsonArray jsonObject = jsonParser.parse(json).getAsJsonArray();
System.out.println(jsonObject);
}
Upvotes: 1