jackson构建复杂Map的序列化
Posted zhshlimi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jackson构建复杂Map的序列化相关的知识,希望对你有一定的参考价值。
1.序列化复杂的Map时,可能需要下面的方式
import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class JsonHelper { public static final ObjectMapper JsonMapper = new ObjectMapper(); /** * String类型的javaType */ public static final JavaType StringJavaType = JsonMapper.getTypeFactory().constructType( String.class); /** * 支持Map<String,String> */ public static final JavaType StringStringMap = JsonMapper.getTypeFactory().constructMapType(HashMap.class, String.class, String.class); /** * 支持Map<String,Map<String,String>> */ public static final JavaType StringStringStringMap = JsonMapper.getTypeFactory() .constructMapType(HashMap.class, StringJavaType, StringStringMap); /** * 支持Map<String,Map<String,Map<String,String>>> */ public static final JavaType StringStringStringStringMap = JsonMapper.getTypeFactory() .constructMapType(HashMap.class, StringJavaType, StringStringStringMap); /** * 支持List<Object> */ public static final JavaType ListObject = JsonMapper.getTypeFactory().constructCollectionType(ArrayList.class, Object.class); /** * 支持List<List<Object>> */ public static final JavaType ListListObject = JsonMapper.getTypeFactory().constructCollectionType(ArrayList.class, ListObject); public static void main(String[] args) { String str = "{ " + ""1": " + "{ " + ""key1": " + " { " + " " + " "a": "1", " + " "b": "1", " + " "c": "a", " + " "d": "2", " + " "e": "1" " + " }, " + " "key2": { " + " "a": "1", " + " "b": "1", " + " "c": "b", " + " "d": "2", " + " "e": "1" " + " } " + " " + "} " + "}"; try { Map<String, Map<String, Map<String, String>>> map = (Map<String, Map<String, Map<String, String>>>) JsonMapper .<Map<String, Map<String, Map<String, String>>>>readValue(str, StringStringStringStringMap); Map<String, String> stringStringMap = map.get("1").get("key1"); System.out.println(stringStringMap); } catch (IOException e) { System.out.println("序列化出错"); } }
以上是关于jackson构建复杂Map的序列化的主要内容,如果未能解决你的问题,请参考以下文章
Jackson:为 Map 数据结构注册自定义 XML 序列化程序
Jackson 将 YAML 文件反序列化为 Map(没有自定义反序列化器)
Jackson中处理map中的null key 或者null value 及实体字段中的null value
MessagePack Java Jackson Dataformat 在 Map 中不使用 String 为 Key 的序列化