简体   繁体   中英

Same named fields with different types in gson parsing

I have a RequestModel defined as

public class RequestModel
{
    public class Footage
    {
        public String date;
        public String retrievedAt;
        public String videoFileName;
        public String availableUntil;
        public boolean isAvailable;
    }

    public class People
    {
        public String first;
        public String last;
    }

    public static final int USER_BLOCKED  = 0;
    public static final int USER_ACTIVE   = 1;
    public static final int USER_WAIT_PIN = 2;

    public String _id;

    public String status;
    public String submittedAt;

    public Footage footage;
    public People teacher;
    public People student;

    public ArrayList<MessageModel> messages = new ArrayList<MessageModel>();
    public boolean isExpanded = false;

    public RequestModel()
    {
    }

My MessageModel is defined as

public class MessageModel
{
    public String _id;

    public String statusMessage;
    public String submittedAt;

    public RequestModel request;
    public String status;
    public String timestamp;

    public boolean isExpanded = false;

    public MessageModel()
    {
    }
}

I have an api call that pulls a single "RequestModel" item. However the messages list in that api call has "request" as a String instead of "RequestModel" object.

Is there any way i can make it parse as a different name or omit it entirely to bypass exceptions causing because of different types.

Use the annotation @SerializedName("") before declaring member to give it a substitute name ex,

if you json looks like this

{
name:"",
age:0,
items:[...]
}

but your model class have the fields,

class User{
    String name;
    int age;
    Data userItems[];
}

The field userItems in model is named items in the json, you need to use that annotation on the field:

class User{
    String name;
    int age;

    @SerializedName("items")
    Data userItems[];
}

this way GSON will map items to userItems .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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