Jackson数据绑定功能可以使用String键和Object值(也可以是地图或集合)将任何json输入读取到Map中。您只是告诉映射器,您想将json读入映射。您可以通过给映射器适当的类型引用来做到这一点:
import java.util.*;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;public class Test{ public static void main(String[] args) { try { String json = "{ " + ""string-property": "string-value", " + ""int-property": 1, " + ""bool-property": true, " + ""collection-property": ["a", "b", "c"], " + ""map-property": {"inner-property": "inner-value"} " + "}"; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = new HashMap<>(); // convert JSON string to Map map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){}); System.out.println("input: " + json); System.out.println("output:"); for (Map.Entry<String, Object> entry : map.entrySet()) { System.out.println("key: " + entry.getKey()); System.out.println("value type: " + entry.getValue().getClass()); System.out.println("value: " + entry.getValue().toString()); } } catch (Exception e) { e.printStackTrace(); } }}输出:
input: { "string-property": "string-value", "int-property": 1, "bool-property": true, "collection-property": ["a", "b", "c"], "map-property": {"inner-property": "inner-value"} }output:key: string-propertyvalue type: class java.lang.Stringvalue: string-valuekey: int-propertyvalue type: class java.lang.Integervalue: 1key: bool-propertyvalue type: class java.lang.Booleanvalue: truekey: collection-propertyvalue type: class java.util.ArrayListvalue: [a, b, c]key: map-propertyvalue type: class java.util.linkedHashMapvalue: {inner-property=inner-value}


