1

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.

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that works (I have tried it too - although mainly with String -> String Maps)
0
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.

2 Comments

Hmm... constructing the JSON string yourself when good libraries exist (see stackoverflow.com/questions/906530/…) isn't necessarily the best way, IMHO.
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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.