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

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

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

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


当前回答

java库可以将json字符串转换为哈希映射。我是这个项目的维护者。

代码示例:

import com.github.underscore.U;
import java.util.*;

public class Main {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String json = "{"
            + "    \"data\" :"
            + "    {"
            + "        \"field1\" : \"value1\","
            + "        \"field2\" : \"value2\""
            + "    }"
            + "}";

       Map<String, Object> data = (Map) U.get((Map<String, Object>) U.fromJson(json), "data");
       System.out.println(data);

       // {field1=value1, field2=value2}
    }
}

其他回答

试试下面的代码:

  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;
    }

我这样做。这很简单。

import java.util.Map;
import org.json.JSONObject;
import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        JSONObject jsonObj = new JSONObject("{ \"f1\":\"v1\"}");
        @SuppressWarnings("unchecked")
        Map<String, String> map = new Gson().fromJson(jsonObj.toString(),Map.class);
        System.out.println(map);
    }
}

JsonTools库非常完整。它可以在Github上找到。

我希望您写自己的解析器是在开玩笑。: -)

对于这样一个简单的映射,http://json.org (java部分)中的大多数工具都可以工作。 对于其中一个(Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator),你会这样做:

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

(其中JSON_SOURCE是文件、输入流、阅读器或json内容字符串)

试试这段代码,对我很管用,

Map<String, Object> retMap = new Gson().fromJson(
                myJsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
        );