为了账号安全,请及时绑定邮箱和手机立即绑定

将 JSON 字符串映射到 HashMap

将 JSON 字符串映射到 HashMap

Helenr 2024-01-05 16:34:57
考虑以下 JSON:[  {    "map": "TEST",    "values": [      "test",      "test2"    ]  },  {    "map": "TEST1",    "values": [      "test",      "test3",      "test4"    ]  },  {    "map": "TEST2",    "values": [      "test4",      "test2",      "test5",      "test2"    ]  }]它们已被 getResourceAsString 函数加载到字符串中。如何制作一个 HashMap,其中我的键是“map”字段,而我的值是“values”字段数组?我在其他类似问题中尝试了很多解决方案,但没有任何效果。这是我的代码的开头:    ObjectMapper mapper = new ObjectMapper();    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);但我不知道如何将它分配给 Map,readValue 方法似乎没有给出正确的东西
查看完整描述

3 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

您可以将其反序列化为List<Map<String, Object>>,然后转换为Map:


import com.fasterxml.jackson.core.type.TypeReference;

import com.fasterxml.jackson.databind.ObjectMapper;


import java.io.File;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


public class JsonApp {


    public static void main(String[] args) throws Exception {

        File jsonFile = new File("./src/main/resources/test.json");


        ObjectMapper mapper = new ObjectMapper();


        TypeReference rootType = new TypeReference<List<Map<String, Object>>>() { };

        List<Map<String, Object>> root = mapper.readValue(jsonFile, rootType);

        Map<String, Object> result = root.stream()

                 .collect(Collectors.toMap(

                         m -> m.get("map").toString(),

                         m -> m.get("values")));

        System.out.println(result);

    }

}

上面的代码打印:


{TEST2=[test4, test2, test5, test2], TEST=[test, test2], TEST1=[test, test3, test4]}



查看完整回答
反对 回复 2024-01-05
?
元芳怎么了

TA贡献1798条经验 获得超7个赞

你可以这样做:


ArrayNode rootNode = (ArrayNode) new ObjectMapper().readTree(...);

Map<String, List<String>> map = new LinkedHashMap<>();

for (int i = 0; i < rootNode.size(); i++) {

    JsonNode objNode = rootNode.get(i);

    String name = objNode.get("map").textValue();

    ArrayNode valuesNode = (ArrayNode) objNode.get("values");

    List<String> values = new ArrayList<>(valuesNode.size());

    for (int j = 0; j < valuesNode.size(); j++)

        values.add(valuesNode.get(j).textValue());

    map.put(name, values);

}

结果


{TEST=[test, test2], TEST1=[test, test3, test4], TEST2=[test4, test2, test5, test2]}



查看完整回答
反对 回复 2024-01-05
?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

您可以List<Map<Object,Object>>将此 json 用作 3 个对象的列表,因此它不能直接转换为 a HashMap,因此请尝试以下操作:

String json = "[{\"map\":\"TEST\",\"values\":[\"test\",\"test2\"]},{\"map\":\"TEST1\",\"values\":[\"test\",\"test3\",\"test4\"]},{\"map\":\"TEST2\",\"values\":[\"test4\",\"test2\",\"test5\",\"test2\"]}]";

List<Map<Object, Object>> jsonObj = mapper.readValue(json, List.class);


查看完整回答
反对 回复 2024-01-05
  • 3 回答
  • 0 关注
  • 56 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信