使用Java和Jackson将Json序列化为无需架构的通用结构

我需要序列化JSON而不附加到结果对象的特定模式,例如,某些通用的set / map / hashmap。

作为输入 ,我有一个带有JSON的字符串。 我不知道那个JSON的架构。

作为输出,我想要一个Java对象,如Hashmap或类似的,具有输入的键值序列化。

请注意,输入JSON包含基本字段和Array / List。

我必须使用Java和Jackson(或其他一些库)。 我怎么可能那样做?

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 map = new HashMap<>(); // convert JSON string to Map map = mapper.readValue(json, new TypeReference>(){}); System.out.println("input: " + json); System.out.println("output:"); for (Map.Entry 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-property value type: class java.lang.String value: string-value key: int-property value type: class java.lang.Integer value: 1 key: bool-property value type: class java.lang.Boolean value: true key: collection-property value type: class java.util.ArrayList value: [a, b, c] key: map-property value type: class java.util.LinkedHashMap value: {inner-property=inner-value}