简体   繁体   中英

map to json object

I am trying to convert a map which is of generic type and contains another map inside it to JSON Object and send it to UI, but I am getting only the parent map, map which is inside it is coming as String.

Example,

      JSONObject obj = new JSONObject();
      Map parent = new HashMap();
      parent.put("key1", "value1");
      Map child = new HashMap();
      child.put("childKey", "childValue");
      parent.put("map1", child);
      obj.put("result", parent);
      return obj.toString();

Please ignore syntax errors. The above code gives me parent map properly that is

parent [key1] - value1

parent [map1] - child

but when I see child its coming as String like child - {childkey=childvalue}

How can I have as array or like parent map for child map also ?

Just a thought here but you might want to take advantage of the Jackson JSON library. Their object mapper and annotations greatly simplifies how you deal with JSON and all but decouples it from your POJOs.

In JSON the top-level object is not named (because it is not a property of another object). So you would just need to add another higher-level object (or array) in order to see the parent named (as a property of the top-level object). But the JSON you produce is already valid and already what I would expect to see as a JavaScript consumer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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