Convert JSON to Map Convert JSON to Map java java

Convert JSON to Map


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 https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:

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

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


Using the GSON library:

import com.google.gson.Gson;import com.google.common.reflect.TypeToken;import java.lang.reclect.Type;

Use the following code:

Type mapType = new TypeToken<Map<String, Map>>(){}.getType();  Map<String, String[]> son = new Gson().fromJson(easyString, mapType);


I like google gson library.
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();