David Nelson David Nelson - 6 months ago 12
JSON Question

Android org.json issues with converting Map to JSON

I have some code to create a specific JSON result in Java (for Android):

Map<String, Object> jsonDict = new HashMap<String, Object>();
Map<String, Object> dict = new HashMap<String, Object>();
dict.put(_operator, _value);
System.out.println("Dict is: " + new JSONObject(dict).toString());

jsonDict.put(_field, dict);
System.out.println("jsonDict is: " + new JSONObject(jsonDict).toString());


When I print out the results of each step is get:

Dict is: {"$eq":"asdf"} // <-- this line is correct


And the final result:

Filter 1 is: {"testing":"{eq=asdf}"} // <-- this line is INCORRECT


The result I should get is:

{"testing":{"eq":"asdf"}}


When I put a
Map
inside the
Object
part of
Map
it switches it to a
String
and adds an = sign. Why does it do this and what can be done about it?

Note: "eq", "asdf", and "testing" are inputs given to my function.

Thanks for your help.

Answer

Try this

JSONObject json=new JSONObject();
json.put("testing",new JSONObject(dict).toString())

output:

{"testing":{"eq":"asdf"}}