How do we convert JSON to Map in Java

0 votes

Which 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? 

Jul 12, 2018 in Java by samarth295
• 2,190 points
249 views

2 answers to this question.

0 votes

For a simple mapping, most tools from http://json.org (section java) would work. 

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

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

answered Jul 12, 2018 by Daisy
• 8,050 points
0 votes

When you don't know structure of json. You can use

JsonElement root = new JsonParser().parse(jsonString);

and then you can work with json. e.g. how to get "value1" from your gson:

String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
answered Oct 31, 2018 by Sushmita
• 6,880 points

Related Questions In Java

+15 votes
18 answers

How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE

answered Feb 7 in Java by Suresh
• 700 points
88,544 views
0 votes
2 answers

How can we convert java.util.Date to java.sql.date in Java?

It's easy to convert a java.util.Date object ...READ MORE

answered Aug 27 in Java by Sirajul
• 37,480 points
82 views
0 votes
2 answers

How do we convert only the second letter of every word in a string to uppercase ?

The following code will perform your desired ...READ MORE

answered Aug 28, 2018 in Java by curious
• 560 points
58 views
0 votes
2 answers

How to convert array into list in Java?

Another workaround if you use apache commons-lang: int[] ...READ MORE

answered Aug 9, 2018 in Java by samarth295
• 2,190 points
53 views
0 votes
2 answers

How to convert a JSON String into Object in Java?

You could probably check out Google's Gson: ...READ MORE

answered Aug 21 in Java by Sirajul
• 37,480 points
400 views
0 votes
1 answer

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?

You can use: new JSONObject(map); READ MORE

answered Jun 27, 2018 in Java by Akrati
• 3,150 points
2,077 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20 in Java by Sirajul
• 37,480 points
187 views
0 votes
2 answers

Integer to String conversion in java

We can do this in 2 ways: String ...READ MORE

answered Jul 27, 2018 in Java by samarth295
• 2,190 points
80 views
0 votes
3 answers

How to parse JSON in Java

import org.json.*; JSONObject obj = new JSONObject(" .... ...READ MORE

answered Aug 20, 2018 in Java by Daisy
• 8,050 points
1,660 views
0 votes
2 answers