David Santamaria David Santamaria - 3 months ago 17
JSON Question

Convert Json to Map

What is the best way to convert a JSON code as this:

{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}


in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2).

Any ideas? Should I use Json-lib for that? Or better if I write my own parser?
Thanks in advance.

Answer

I hope you were joking about writing your own parser. :-)

For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson, http://wiki.fasterxml.com/JacksonInFiveMinutes), you'd do:

HashMap<String,Object> result =
        new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);

(where JSON_SOURCE is a File, input stream, reader, or json content String)