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:54

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);
查看更多
低头抚发
3楼-- · 2019-01-01 05:54

With google's Gson 2.7 (probably earlier versions too, but I tested 2.7) it's as simple as:

Map map = gson.fromJson(json, Map.class);

Which returns a Map of type class com.google.gson.internal.LinkedTreeMap and works recursively on nested objects.

查看更多
登录 后发表回答