简体   繁体   中英

How to convert string in json to json object

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.

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);

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){
 // 
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM