【问题标题】:Jackson JSON Array Value DeserializationJackson JSON 数组值反序列化
【发布时间】:2017-03-10 17:49:21
【问题描述】:

我正在尝试使用 Jackson 2.8 反序列化这个 JSON 对象作为改造响应的一部分。这是我从服务器获得的 JSON 响应。

{
 "id":"8938209912"
 "version":"1.1"
 "cars":{  
    "mercedes":[  
       {  
          "property":"color"
       },
       {  
          "property":"price"
       },
       {  
          "property":"location"
       }
    ],
    "tesla":[  
       {  
          "property":"environment"
       }
    ]
  }
}

根据查询,上面的cars 可能返回一个或多个模型。我不能为每个模型创建一个类,因为它们是任意创建/删除的。对于汽车的每个型号(比如tesla),可能有一个或多个property 键值对。

我是Jackson 的新手。我一直在看几个例子,看起来自定义@JsonDeserialize 是最好的方法。所以,我像这样创建了Root 类和Cars 类:

 // In file Root.java
 public class Root {
    @JsonProperty("id")
    private String id = null;


    @JsonProperty("version")
    private String version = null;

    @JsonProperty("cars")
    private Cars cars = null;
 }

 // In file Cars.java
 public class Cars {

    public Cars(){} 

    @JsonDeserialize(using = CarDeserializer.class)
    private Map<String, List<Property>> properties; 

    public Map<String, List<Property>> getProperties() {
        return properties;
    }

    public void setProperties(Map<String, List<Property>> properties) {
        this.properties = properties;
    }   
 }

 // Property.java
 public class Property {

   @JsonProperty("property")
   private String property;
 }

我的反序列化器在下面。但是,即使调用了空构造函数,解析方法本身也没有被调用!

     // CarDeserializer.class
     public class RelationshipDeserializer extends StdDeserializer<Map<String, List<Action>>>{

         protected RelationshipDeserializer(){
            super(Class.class);
         }  

        @Override
        public Map<String, List<Action>> deserialize(JsonParser parser, DeserializationContext ctx)
        throws IOException, JsonProcessingException 
        {
             // This method never gets invoked.
        }
     }

我的问题:

  1. 首先这是正确的方法吗?
  2. 为什么你认为执行永远不会到达deserialize()? (我检查了,cars 对象存在于 JSON 中。
  3. 是否有更好的方法来使用 Jackson 解析此 JSON?

【问题讨论】:

    标签: java json jackson deserialization


    【解决方案1】:

    永远不会调用“属性”反序列化程序,因为它与该 JSON 中的任何内容都不匹配。 JSON 中的字段名称为“property”,与Map&lt;String, List&lt;Property&gt;&gt; 不匹配。看起来会更接近List&lt;Property&gt;

    你控制传入的 JSON 吗?最好将汽车名称/类型放在自己的字段中,而不是对象的名称中。然后您可以使用通用对象。你现在拥有的东西会坏掉。每当他们添加新名称/类型而您没有匹配的对象时。

    【讨论】:

    • 很遗憾,我无法控制从服务器传入的 JSON。
    猜你喜欢
    • 2021-06-22
    • 1970-01-01
    • 2015-02-28
    • 2012-08-19
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2013-08-22
    相关资源
    最近更新 更多