Reputation: 501
I have this json string
{
"team": "xyz",
"patern": "abc",
"service": "{\"version\":0,\"name\":\"some_service_name\"}",
"op": "{\"version\":0,\"name\":\"some_op_name\"}",
.
.
.
}
and would like to convert it into JsonObject, since it has a json string inside I have to pull out the JsonElement and then use it. The problem is JsonElement "service" and "op" are String
I would like the JsonObject to be converted like this
{
"team": "xyz",
"patern": "abc",
"service": {"version":0,"name":"some_service_name"},
"op": {"version":0,"name":"some_op_name"},
.
.
.
}
I have tried new JsonParser().parse(string) and also new Gson().fromJson(string, JsonObject.class) but it doesn't resolve. Also tried Jolt but it parses it as String.
I know that this can be solved by mapping it to a java class and then use it but I would like to know if there is a way to get away without additional java class.
Upvotes: 3
Views: 2736
Reputation: 603
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"team\": \"xyz\",\"patern\": \"abc\",
\"service\": \"{\"version\":0,\"name\":\"some_service_name\"}\",
\"op\": \"{\"version\":0,\"name\":\"some_op_name\"}\" }");
For more ways check this link
http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html
Upvotes: 0
Reputation: 11
This might help you!
JSONEqualentBeanClass jSONEqualentBeanClass = null;
com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
try{
jSONEqualentBeanClass = mapper.readValue(yourJSONStr, JSONEqualentBeanClass.class);
}catch(Exception e){
//
}
Upvotes: 0
Reputation: 543
I have not found a way to do this. Using Gson though works quite well. I would do something like this.
Gson gson = new Gson();
Map res = gson.fromJson(string, Map.class);
Map service = gson.fromJson((String)res.get("service"), Map.class);
Map op = gson.fromJson((String)res.get("op"), Map.class);
res.put("service", service);
res.put("op", op);
String newString = gson.toJson(res);
Upvotes: 2