D
D
Denis2017-08-04 21:43:17
Java
Denis, 2017-08-04 21:43:17

How to handle changing json object type using gson?

Good day!
I am using the gson library in my project.
Using the standard way, creating a json object class

spoiler
package ru.grozny.charity.groznycharitablefoundation.models;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class PaginationModel implements Parcelable {
    @SerializedName("total")
    @Expose
    private int totalCount;
    @SerializedName("count")
    @Expose
    private int count;
    @SerializedName("per_page")
    @Expose
    private int perPage;
    @SerializedName("current_page")
    @Expose
    private int currentPage;
    @SerializedName("total_pages")
    @Expose
    private int totalPages;
    @SerializedName("links")
    @Expose
    private LinksModel links;

    public static final Parcelable.Creator<PaginationModel> CREATOR =
            new Parcelable.Creator<PaginationModel>() {

                public PaginationModel createFromParcel(Parcel in) {
                    return new PaginationModel(in);
                }

                public PaginationModel[] newArray(int size) {
                    return new PaginationModel[size];
                }
            };

    private PaginationModel(Parcel parcel) {
        totalCount = parcel.readInt();
        count = parcel.readInt();
        perPage = parcel.readInt();
        currentPage = parcel.readInt();
        totalPages = parcel.readInt();
        links = parcel.readParcelable(LinksModel.class.getClassLoader());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(totalCount);
        dest.writeInt(count);
        dest.writeInt(perPage);
        dest.writeInt(currentPage);
        dest.writeInt(totalPages);
        dest.writeParcelable(links, 30);
    }

    public int getTotalCount() {
        return totalCount;
    }

    public int getCount() {
        return count;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public LinksModel getLinks() {
        return links;
    }
}


Json comes from the server in which there is a links field, which can come in the form of a json object or in the form of a json array.
Accordingly, in the current state, json parsing does not work if links comes in the form of an array.
Please tell me how to proceed in this case.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-08-04
@lacredin

Well, sobsno, write your own adapter for this field. And fuck it how you want

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question