0
import org.json.JSONArray;
import org.json.JSONObject;

    HashMap<String,String> testAttMap = new HashMap<String,String>();
        HashMap<String,String> jsonMap = new HashMap<String,String>();
        jsonMap.put("containerType", "Drive");
        testAttMap.put("idNbr", "11111111111");
        testAttMap.put("name", "ATTTT");
        jsonMap.put("testAtts", new JSONObject(testAttMap).toString());
        System.out.println(new JSONArray().put(jsonMap));   

Expecting :

[{"containerType":"Drive","testAtts":"{"idNbr":"11111111111","name":"ATTTT"}"}]

Actual Result :

[{"containerType":"Drive","testAtts":"{\"idNbr\":\"11111111111\",\"name\":\"ATTTT\"}"}]

Can anyone suggest a fix?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
sankardev51
  • 37
  • 1
  • 6
  • 1
    `jsonMap.put("testAtts", new JSONObject(testAttMap).toString());` - you're explicitly converting the object `toString`, it's unclear to me why that output is unexpected. – jonrsharpe Mar 16 '19 at 23:11
  • Use a String,Object map and Simply assign the `testAtts` key the value of the other map? – ivanivan Mar 17 '19 at 00:48
  • Possible duplicate of [How to convert hashmap to JSON object in Java](https://stackoverflow.com/questions/12155800/how-to-convert-hashmap-to-json-object-in-java) – FlorianDe Mar 17 '19 at 11:04

1 Answers1

2

What you want to do is simply:

jsonMap.put("testAtts", new JSONObject(testAttMap));

instead of

jsonMap.put("testAtts", new JSONObject(testAttMap).toString());

the slashes are there because you are escaping the double quotes

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • not sure what you're talking about, why would it fail with string values – Alexander Mills Mar 16 '19 at 23:13
  • It wouldn't fail with string values (it won't error, just have an outcome other than the one the OP wants), but you're suggesting a `JSONObject` value. Did you actually try this? – jonrsharpe Mar 16 '19 at 23:14
  • `jsonMap` is declared as `HashMap jsonMap` which is probably why OP called `toString()` on it. – Pshemo Mar 16 '19 at 23:18
  • I am not sure why it is downvoted. Removing `toString` call is right step. Other step required is changing type of `jsonMap` to something which can store as value string and other objects so `Map` comes to mind (since we don't want to use raw types). – Pshemo Mar 16 '19 at 23:21
  • I am not sure why people are saying Object is required instead of String in the map, all I see is these two calls `testAttMap.put("idNbr", "11111111111"); testAttMap.put("name", "ATTTT");` – Alexander Mills Mar 16 '19 at 23:44
  • 1
    Because you're presumably looking at the inner object `testAttMap`, not the outer one `jsonMap`, which is also `HashMap` but into which you're nonetheless trying to put a `JSONObject` value? That's just how types work. – jonrsharpe Mar 16 '19 at 23:46