使用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