jasminb / jsonapi-converter

JSONAPI-Converter is a Java/Android library that provides support for working with JSONAPI spec
Apache License 2.0
273 stars 81 forks source link

Help: Is there any options to parse this json? Generic type. #221

Open ExtinctAmoeba opened 5 years ago

ExtinctAmoeba commented 5 years ago

Json: https://jsonblob.com/96555bba-be78-11e9-bd8b-cdbff37ad6cb

It has generic type and I cannot find any solution for this issue.

ExtinctAmoeba commented 5 years ago

@jasminb Can You please help me with this?

jasminb commented 5 years ago

Hello @ExtinctAmoeba, this can be achieved in following way:

Write a base class like this (having in mind that attributes are similar in both sub-types, your base class can hold all of the common attributes, below is a just simple example):

public class BaseModel {

    @Id
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

And than write two different classes for each of your types (Movie and Vod):

@Type("Movie")
public class Movie extends BaseModel {
    private Integer categoryId;

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }
}
@Type("Vod")
public class Vod extends BaseModel {

    private Integer categoryId;

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }
}

Make sure to register both types with ResourceConverter instance.

To handle response, do:

JSONAPIDocument<List<BaseModel>> elements = converter.readDocumentCollection(data, BaseModel.class);