skip to Main Content

My response as below and I want to convert it to json object but I don’t know how to do it. 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

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

2

Answers


  1. The string you want to convert is not in the JSON format. 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 }.

    Following the comment from @tgdavies if you get the response from some server, ask for clarification. If you just do this yourself, then this string is the correct format for the json file you want.

    {"m_list":[{"contract":{"category":1,"cor_num":101,"contract_name":"ABC"},"bu_unit":{"bu_name":"1-1E"}}]}
    
    Login or Signup to reply.
  2. You can use library Josson to restore the JSON object/array from a string inside a JSON.

    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

    {
      "m_list" : [ {
        "contract" : {
          "category" : 1,
          "cor_num" : 101,
          "contract_name" : "ABC"
        },
        "bu_unit" : {
          "bu_name" : "1-1E"
        }
      } ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search