简体   繁体   English

Gson在包装器中反序列化模型

[英]Gson deserialize models within a wrapper

I've got a collection of potential JSON response models within a wrapper class, such as this Dashboard example: 我在包装器类中有一组潜在的JSON响应模型,例如这个Dashboard示例:

public class Dashboard {

    @SerializedName("dashboard")
    private List<Wrapper> wrappers;

    public class Wrapper {

         LocalDateTime updated;

         SingleItemModel item;

         ItemCollectionModel items;

         //....

    }
}

public class ItemCollectionModel {

      List<SingleItemModel> items;

}

I'm trying to populate these fields from an aggregated JSON of several API endpoints. 我正在尝试从几个API端点的聚合JSON填充这些字段。 An abbreviated form looks similar to this: 缩写形式看起来类似于:

{
   "dashboard": [
   {
      "updated": "2017-02-08T05:42:52.451",
      "items": {...}
    },
      "updated": "2017-02-08T05:42:52.451",
      "item": {...}
    },
    ....
    ]
}

I'm having an issue where Gson is failing to create the POJOs. 我遇到了Gson无法创建POJO的问题。 If my understanding is correct, the default deserialization attempts to match the field name with the JSON element key. 如果我的理解是正确的,则默认反序列化会尝试将字段名称与JSON元素键匹配。

"items" : {} to ItemCollectionModel items

I think the problem is that the instance fields are named similarly to their Wrappers counterpart. 我认为问题是实例字段的命名方式与它们的Wrappers相似。

Wrapper.items vs ItemCollectionModel.items

The Gson deserialization works perfect when the API response is a single POJO, it treats the encapsulating JSON object as the POJO and the inner values of the JSON are matched to the POJO fields. 当API响应是单个POJO时,Gson反序列化非常有效,它将封装JSON对象视为POJO,JSON的内部值与POJO字段匹配。 But I'm getting null fields when attempting to use the Wrapper. 但是在尝试使用Wrapper时我得到了空字段。

How can I ensure that the Wrapper's fields are correctly deserialized? 如何确保Wrapper的字段正确反序列化?

------------UPDATE------------- ------------ UPDATE -------------

A simple solution was staring me in the face. 一个简单的解决方案就是盯着我。 Using a List of objects, per jakubbialkowski's answer, allows Gson to deserialize the items. 根据jakubbialkowski的答案,使用对象列表,允许Gson反序列化项目。 The trick was to then just manually create the CollectionModel to encapsulate it when the getter for the field is called. 诀窍是然后手动创建CollectionModel以在调用字段的getter时封装它。

public ItemCollectionModel getItemCollectionModel() {
    return new ItemCollectionModel(items);
}

Try to replace : 尝试替换:

ItemCollectionModel items;

with: 有:

List<SingleItemModel> items;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM