简体   繁体   English

如何将响应从字符串转换为 jsonObject?

[英]How to convert a Response from string to jsonObject?

My response as below and I want to convert it to json object but I don't know how to do it.我的回复如下,我想将其转换为 json object 但我不知道该怎么做。 Could you guide me?你能指导我吗? Thank you: Response:谢谢: 回复:

{"m_list": "[{\"contract\":{\"category\":1,\"cor_num\":101,\"contract_name\":\"ABC\"},\"bu_unit\":{\"bu_name\":\"1-1E\"}}]"}

My expected => It'll convert as a json object as below我的预期=>它将转换为 json object 如下

{ m_list: 
   [ { contract: 
        { category: 1,
          cor_num: 101,
          contract_name: 'ABC'},
       bu_unit: { bu_name: '1-1E' }} ] }

I tried the following way but seem it didn't work我尝试了以下方法,但似乎没有用

JSONObject jsonObject = new JSONObject(str) JSONObject jsonObject = new JSONObject(str)

The string you want to convert is not in the JSON format.您要转换的字符串不是 JSON 格式。 From the official documentation of JSON https://www.json.org/json-en.html - it has to start with left brace {, and end with right brace }.来自 JSON https://www.json.org/json-en.html的官方文档 - 它必须以左大括号 { 开始,以右大括号 } 结束。

Following the comment from @tgdavies if you get the response from some server, ask for clarification.按照@tgdavies 的评论,如果您从某个服务器得到响应,请要求澄清。 If you just do this yourself, then this string is the correct format for the json file you want.如果你只是自己做这个,那么这个字符串就是你想要的 json 文件的正确格式。

{"m_list":[{"contract":{"category":1,"cor_num":101,"contract_name":"ABC"},"bu_unit":{"bu_name":"1-1E"}}]}

You can use library Josson to restore the JSON object/array from a string inside a JSON.您可以使用库Josson从 JSON 中的字符串恢复 JSON 对象/数组。

https://github.com/octomix/josson https://github.com/octomix/josson

Deserialization反序列化

Josson josson = Josson.fromJsonString(
    "{\"m_list\": \"[{\\\"contract\\\":{\\\"category\\\":1,\\\"cor_num\\\":101,\\\"contract_name\\\":\\\"ABC\\\"},\\\"bu_unit\\\":{\\\"bu_name\\\":\\\"1-1E\\\"}}]\"}");

Transformation转型

JsonNode node = josson.getNode("map(m_list.json())");
System.out.println(node.toPrettyString());

Output Output

{
  "m_list" : [ {
    "contract" : {
      "category" : 1,
      "cor_num" : 101,
      "contract_name" : "ABC"
    },
    "bu_unit" : {
      "bu_name" : "1-1E"
    }
  } ]
}

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

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