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 got this error: A JSONObject text must begin with '{' at 1 [character 2 line 1]
JSONObject jsonObject = new JSONObject(str)
CodePudding user response:
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"}}]}
CodePudding user response:
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"
}
} ]
}