Convert JSON to Map

2019-01-01 04:58发布

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?

14条回答
千与千寻千般痛.
2楼-- · 2019-01-01 05:30

This way its works like a Map...

JSONObject fieldsJson = new JSONObject(json);
String value = fieldsJson.getString(key);

<dependency>
    <groupId>org.codehaus.jettison</groupId>
    <artifactId>jettison</artifactId>
    <version>1.1</version>
</dependency>
查看更多
梦寄多情
3楼-- · 2019-01-01 05:36

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)

查看更多
梦寄多情
4楼-- · 2019-01-01 05:37

JSON to Map always gonna be a string/object data type. i haved GSON lib from google.

works very well and JDK 1.5 is the min requirement.

查看更多
旧人旧事旧时光
5楼-- · 2019-01-01 05:38
import net.sf.json.JSONObject

JSONObject.fromObject(yourJsonString).toMap
查看更多
伤终究还是伤i
6楼-- · 2019-01-01 05:44

One more alternative is json-simple which can be found in Maven Central:

(JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.

The artifact is 24kbytes, doesn't have other runtime dependencies.

查看更多
路过你的时光
7楼-- · 2019-01-01 05:45

Use JSON lib E.g. http://www.json.org/java/

// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
    String name = nameItr.next();
    outMap.put(name, jdata.getString(name));

}
查看更多
登录 后发表回答