如何从JsonNode获取键值映射?

时间:2019-02-13 05:26:39

标签: json jackson jsonpath

我有以下JSON文件。

{
  "data": {
    "k1": "v1",
    "k2": "v2",
    ...
  }
}

有什么方法可以使用路径路径将这些键和值作为Map<String, String>来获取?

我目前正在这样做。

JsonNode root = ...
JsonNode data = root.get("data");
ObjectReader reader = mapper.readFor(new TypeReference<Map<String, String>>(){});
reader.readValue(data);

2 个答案:

答案 0 :(得分:1)

以下是会话示例:

ObjectMapper objectMapper = new ObjectMapper();
        JsonNode root = objectMapper.readTree("{\n" +
                "  \"data\": {\n" +
                "    \"k1\": \"v1\",\n" +
                "    \"k2\": \"v2\"\n" +
                "  }\n" +
                "}");
        Map<String,String> map = objectMapper.convertValue(root.get("data"),Map.class);

答案 1 :(得分:0)

您可以创建简单的POJO,如下所示:

class Data {
    private Map<String, String> data;

    public Map<String, String> getData() {
        return data;
    }

    public void setData(Map<String, String> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Data{" +
                "data=" + data +
                '}';
    }
}

以这种方式阅读JSON

ObjectMapper mapper = new ObjectMapper();
Data data = mapper.readValue(jsonFile, Data.class);
System.out.println(data);

上面的代码显示:

Data{data={k1=v1, k2=v2}}