如何解析动态列表与Gson注释? [英] How to parse Dynamic lists with Gson annotations?

查看:110
本文介绍了如何解析动态列表与Gson注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Retrofit和Gson来查询一个API,但是我从来没有遇到像这样的JSON响应。



响应:

  {
响应:{
Black:[
{id:123,code :RX766},
{id:324,code:RT344}],
Green:[
{id:3532 ,code:RT983},
{id:242,code:RL982}],
Blue:[
{id :453,code:RY676},
{id:134,code:R67HJH}]
}
}

问题是列表元素id例如black是动态的,所以我不知道他们会是什么



到目前为止,我已经为内部类型创建了一个类;

  class Type {
@SerializedName(id)private String id;
@SerializedName(code)private String code;
}

有可能有以下情况吗?

  class Response {

@SerializedName(response)
List< Type>类型;
}

然后将列表ID移动到该类型中,所以Type类将变为;

  class类型{
@SerializedName(id)private String id;
@SerializedName(code)private String code;
@SerializedName($)private String type; //不知道如何填充它
}

如果不是,那该怎么办?只用Gson属性进行解析?



好的,我刚刚看到了这个问题;
如何使用GSON解析动态JSON字段?



看起来不错,是否可以用响应对象包装泛型地图?

解决方案

如果键是动态的,你需要一张地图。

  class Response {
@SerializedName(response)
Map< String,List< Type>>类型;
}

反序列化后,您可以将类型转换为更多语义的类型。 / p>

如果这不合适,您需要注册 TypeAdapter JsonDeserializer code>并将类地图数据自定义反序列化为简单的 List


I am using Retrofit and Gson to query an API, however I have never come across a JSON response like it.

The Response:

{
    Response: {
        "Black":[
            {"id":"123","code":"RX766"},
            {"id":"324","code":"RT344"}],
        "Green":[
            {"id":"3532","code":"RT983"},
            {"id":"242","code":"RL982"}],
        "Blue":[
            {"id":"453","code":"RY676"},
            {"id":"134","code":"R67HJH"}]
    }
}

The problem is the list elements id eg "black" is dynamic, so I a have no idea what they will be.

So far I have created a class for the inner type;

class Type {
    @SerializedName("id") private String id;
    @SerializedName("code") private String code;
}

Is it possible to have the following?

class Response {

    @SerializedName("response")
    List<Type> types;
}

And then move the list ID into the type, so the Type class would become;

class Type {
    @SerializedName("id") private String id;
    @SerializedName("code") private String code;
    @SerializedName("$") private String type; //not sure how this would be populated
}

If not, how else could this be parsed with just Gson attributes?

Ok so I have just seen this question; How to parse dynamic JSON fields with GSON?

which looks great, is it possible to wrap a generic map with the response object?

解决方案

If the keys are dynamic you want a map.

class Response {
    @SerializedName("response")
    Map<String, List<Type>> types;
}

After deserialization you can coerce the types into something more semantic in your domain.

If this is not suitable you will need to register a TypeAdapter or a JsonDeserializer and do custom deserialization of the map-like data into a simple List.

这篇关于如何解析动态列表与Gson注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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