将JSON解析为Map< String,Entity>与FlexJSON [英] Parsing JSON into Map<String, Entity> with FlexJSON

查看:204
本文介绍了将JSON解析为Map< String,Entity>与FlexJSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析与此类似的JSON结构:

I am trying to parse a JSON structure similar to this one:

    {
 "cars": {
  "112": {
   "make": "Cadillac",
   "model": "Eldorado",
   "year": "1998"
  },
  "642": {
   "make": "Cadillac",
   "model": "Eldorado",
   "year": "1990"
  },
  "9242": {
   "make": "Cadillac",
   "model": "Eldorado",
   "year": "2001"
  }
 }}

我有一个CarEntity类,其中定义了makeName,model,year属性,可以通过设置器/获取器进行访问.

I have a CarEntity class defined with makeName,model,year attributes defined and accessible via setters/getters.

我正在尝试反序列化此JSON:

I am trying to deserialize this JSON like this:

    Map<String, CarEntity> deserialized = new JSONDeserializer<Map<String, CarEntity>>()
   .use("cars.values", Map.class)
   .deserialize(json);

它不起作用:(它确实对它进行了反序列化,但不是对Map<String, CarEntity>进行反序列化,而是对深度Map(类似于Map<String, Map<String, Map<String, String>>>之类的东西)

and it doesn't work :( It does deserialize it but not into Map<String, CarEntity> but rather into deep Map(something like Map<String, Map<String, Map<String, String>>> )

我在做什么错了?

推荐答案

您的问题是您的json有两个地图.一个包含"cars"键,另一个包含实际的CarEntity.不幸的是,此时您不能在Map中引用单个键,而只能在该键上分配类型.通常,在集合的值上设置类型是指集合中的所有值.您无需为第一个包含"cars"键的地图指定类型,因为默认情况下它将反序列化.

You're problem is your json has two maps. One which contains the 'cars' key, and one that contains the actual CarEntity. Unfortunately, you can't refer to a single key within a Map and assign types on just that key at this time. Generally setting types on values for collections refers to all values within the collection. You don't need to specify the types for the first Map that contains the "cars" key since it will deserialize it by default.

Map<String, CarEntity> deserialized = new JSONDeserializer<Map<String,Map<String, CarEntity>>>()
    .use("values.values", CarEntity.class )
    .deserialize(json).get("cars");

路径"values.values"是指外部Map的值,然后遍历下一个地图的值都是所有CarEntity实例.

The path 'values.values' refers to the outer Map's values then traversing the next map values are all CarEntity instances.

我已经考虑过将路径表达式更改为更具表达性,以使您可以定位集合中的单个值,但这增加了评估它们的开销,并且向后兼容是一个挑战.

I've considered changing the path expressions to be more expressive allowing you to target a single value in a collection, but this increases overhead of evaluating them and being backwards compatible is a challenge.

这篇关于将JSON解析为Map&lt; String,Entity&gt;与FlexJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆