How to convert a LinkedHashMap<String, List<Node>> into a JSONObject?

Simone Colnaghi :

I'm new at JSONObject and I'm trying to convert a LinkedHashMap<String, List<Node>> into a json file. The map is structured in this way:

"element_one", {Node1, Node2, etc...}
"element_two", {Node1, Node2, etc...}

Every Node has two properties: value and label.

What I want is something like this:

{
"element_one": [
{
"items": [
  {
    "value": "1",
    "label": "Donald"
  },
  {
    "value": "2",
    "label": "Goofy"
  }]
}],

"element_two": [
{
"items": [
  {
    "value": "1",
    "label": "Peter"
  },
  {
    "value": "2",
    "label": "Wendy"
  }]
}}

I'm using JSONObject and I looked for a solution in different thread but nothing helped me. I know this is a particolar question, but I need to have this result with this data structure.

The hard point is to loop the nodes element inside the map without overwrite the elements already inserted in the JSONObject.

Thanks.

Simone Colnaghi :

I solved it combining JSONArray and JSONObject class.

I've created the main object using a loop for all the nodes:

for (Node node : nodeList)
{
  try
  {
     JSONObject obj = new JSONObject();
     obj.put("value", node.getValue());
     obj.put("label", node.getLabel());
     jsonArrayOne.put(obj)
  }
  catch (JSONException e)
  {
     log.info("JSONException");
  }
}

Then put the jsonArrayOne in a jsonObject:

jsonObjOne.put("items", jsonArrayOne);

And put this jsonObjOne into an jsonArray:

jsonArrayTwo.put(jsonObjOne);

Put this jsonArrayTwo in a jsonObject:

jsonObjTwo.put(element, jsonArrayTwo);

Finally put this jsonObjTwo into the jsonArrayFinal.

jsonArrayFinal.put(jsonObjTwo);

At the end I converted the jsonArrayFinal into a String:

jsonArrayFinal.toString();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166537&siteId=1