Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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?

1 Answer

0 votes
by (46k points)

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)

Related questions

+10 votes
2 answers
asked May 30, 2019 in Java by tommas (1k points)
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 26, 2019 in Java by Krishna (2.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...