-
温温酱
您可以将其反序列化为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]}
-
元芳怎么了
你可以这样做: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]}
-
宝慕林4294392
您可以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);