如何使用Gson为多个JSON对象编写TypeAdapter?

时间:2017-05-03 13:45:22

标签: java android json gson retrofit

我有一个带有多个嵌套JSON对象的JSON提要。我编写了我的POJO类,并在这里查看了如何反序列化嵌套的JSON对象以访问我需要的数据。但是我仍然在我的嵌套JSON对象上收到NullPointerException

JSON提要示例

{
    "data": [
        {
            "relationships": {
                "dismissals": {
                    "meta": {
                        "count": {
                            "home": 0,
                            "away": 0
                        }
                    },
                    "data": []
                },
                "home": {
                    "data": {
                        "type": "teams",
                        "id": "2"
                    }
                }
            }
        }
    ]
}        

Pojo Mappings

关系:

public class Relationships implements Serializable

    @SerializedName("region")
    @Expose
    private Region region;
    @SerializedName("competition")
    @Expose
    private Competition competition;

getters and setters

}

区:

public class Region implements Serializable
{

    @SerializedName("data")
    @Expose
    private Data data;

}

数据

public class Data implements Serializable, Parcelable
{

    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("id")
    @Expose
    private String id;

}

我的TypeAdapter

public class ItemTypeDataFactory implements TypeAdapterFactory {

    public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
        final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

        return new TypeAdapter<T>() {

            public void write(JsonWriter out, T value) throws IOException {
                delegate.write(out, value);
            }

            public T read(JsonReader in) throws IOException {

                JsonElement jsonElement = elementAdapter.read(in);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();

                }

                return delegate.fromJsonTree(jsonElement);
            }
        }.nullSafe();
    }}

改造生成器:

 Gson gson = new GsonBuilder()
                .registerTypeAdapterFactory(new ItemTypeDataFactory()) // This is the important line ;)
                .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);

例如我想得到:

getRelationships().getDissmissals().Meta().Count().Home();

当我运行我的应用时,我得到NullPointerException

我是否需要添加到我的类型适配器以反序列化类,以便我可以在多个嵌套的JSON对象中获取数据?我已经尝试过在这里查看,没有任何帮助。

1 个答案:

答案 0 :(得分:0)

有时很难为JSON响应生成POJO类。 您可以在http://www.jsonschema2pojo.org/

轻松生成您的POJO