转换JSON代码的最佳方法是什么:

{ 
    "data" : 
    { 
        "field1" : "value1", 
        "field2" : "value2"
    }
}

在Java Map中,其中一个键是(field1, field2),这些字段的值是(value1, value2)。

什么好主意吗?我应该使用Json-lib吗?或者如果我自己编写解析器会更好?


当前回答

使用GSON库:

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

使用以下代码:

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

其他回答

另一个选择是json-simple,可以在Maven Central中找到:

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

工件是24kbytes,没有其他运行时依赖项。

试试下面的代码:

  public static Map<String, Object> convertJsonIntoMap(String jsonFile) {
        Map<String, Object> map = new HashMap<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
            mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {
            });
            map = mapper.readValue(jsonFile, new TypeReference<Map<String, String>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

使用JSON库,例如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));

}

使用谷歌的Gson 2.7(可能是更早的版本,但我测试了2.7),它很简单:

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

它返回类型为com.google.gson.internal.LinkedTreeMap的Map,并对嵌套对象递归地工作。

JSON to Map总是字符串/对象数据类型。我有GSON lib从谷歌。

工作得非常好,JDK 1.5是最低要求。