Json反序列化Map的key不能是Object

栏目: 后端 · 前端 · 发布时间: 8年前

内容简介:Json反序列化Map的key不能是Object
使用json作为数据传输格式,碰到一个问题。我希望传输的是一个Map<Target, TargetInfo>
其中Target是一个对象,作为map的一个key
public class Target{
    private String id;
    private String value;
}

使用json序列化 工具 可以将这个map成功的序列化,如下所示:

@Test
public void test() {
    Map<Target, String> map = new HashMap<>();
    map.put(new Target(TargetType.CATEGORY, "124"), "124");
    log.info("json = {}", JsonUtils.toJson(map));
    MapInfo res = (MapInfo) JsonUtils.fromJson(" {\"Target(type=CATEGORY, value=124)\":\"124\"}", MapInfo.class);
    log.info("res = {}", res);
}

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class MapInfo {
    private Map<Target, String> mapInfo;
} 

可是如果进行反序列化,会报如下错误:

json utils from json failed, content = {"Target(type=CATEGORY, value=124)":"124"}, type = exception message = Can not find a (Map) Key deserializer for type [simple type, class com.baidu.bce.mkt.oss.model.brokerage.Target]

at [Source: {"Target(type=CATEGORY, value=124)":"124"}; line: 1, column: 2]

所以,进行数据传输的时候,尽量优化一下数据结构,不要使用Object作为map的key

本文永久更新链接地址 http://www.linuxidc.com/Linux/2017-06/144476.htm


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning ASP.NET 4 in C# and Vb

Beginning ASP.NET 4 in C# and Vb

Imar Spaanjaars / Wrox / 2010-3-19 / GBP 29.99

This book is for anyone who wants to learn how to build rich and interactive web sites that run on the Microsoft platform. With the knowledge you gain from this book, you create a great foundation to ......一起来看看 《Beginning ASP.NET 4 in C# and Vb》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具