简体   繁体   English

如何将json中的字符串转换为json对象

[英]How to convert string in json to json object

I have this json string我有这个 json 字符串

{
  "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.并想将其转换为 JsonObject,因为它里面有一个 json 字符串,我必须拉出 JsonElement 然后使用它。 The problem is JsonElement "service" and "op" are String问题是 JsonElement "service" 和 "op" 是 String

I would like the JsonObject to be converted like this我希望 JsonObject 像这样转换

   {
      "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.我已经尝试过 new JsonParser().parse(string) 和 new Gson().fromJson(string, JsonObject.class) 但它没有解决。 Also tried Jolt but it parses it as String.也试过 Jolt,但它把它解析为字符串。

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.我知道这可以通过将它映射到一个 java 类然后使用它来解决,但我想知道是否有办法在没有额外的 java 类的情况下脱身。

I have not found a way to do this.我还没有找到一种方法来做到这一点。 Using Gson though works quite well.虽然使用 Gson 效果很好。 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:使用org.json库:

 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 http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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