tags:

views:

923

answers:

2

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.

A: 
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.

José Leal
Hmm... constructing the JSON string yourself when good libraries exist (see http://stackoverflow.com/questions/906530/using-json-to-return-a-java-map/906563#906563) isn't necessarily the *best* way, IMHO.
Jonik
More importantly, this fails to produce correct JSON in some cases, e.g. when the strings contain ' characters. (And this would not be fixed by quoting also the key, which you don't do now.)
Jonik
+6  A: 

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.

coobird
Yeah, that works (I have tried it too - although mainly with String -> String Maps)
Jonik
Great, thank you for letting me know! :)
coobird