javaarraysjsonparsingkatalon-studio

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


Solution

  • 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"
        }
      } ]
    }