Reputation: 10070
What's the best way to return a Java Map using the JSON format? My specific need is a key -> value association between a date and a number.
My concern is this: My structure basically contains N elements of the same type (a mapping between a date and a number), and I want to be able to quickly iterate through them in Javascript.
In XML, I would have:
<relation date='mydate' number='mynumber'/>
<relation date='mydate' number='mynumber'/>
...
<relation date='mydate' number='mynumber'/>
and I would use jQuery like this:
$(xml).find("relation").each(function() {
$(this).attr("date"); // the date
$(this).attr("number"); // the number
})
It's my first experience with JSON and I would like to know if I can do something similar.
Upvotes: 1
Views: 5199
Reputation: 161022
Although I haven't tried it myself, the JSONObject
of the Java implementation of JSON from json.org has a JSONObject(Map)
constructor.
Once a JSON object is created from the Map
, then a JSON string can be obtained by calling the toString
method.
Upvotes: 8
Reputation: 8109
String myJson = "{ ";
for (String key : myMap.keySet())
myJson += key + " : " + "'" + myMap.get(key) + "',";
myJson += " } ";
I leave the last comma because it wont give us many problems. The javascript just ignores it.
Well, this respond your question but I guess that won't help much. Try posting a more specific one.
Upvotes: 0