简体   繁体   中英

Android , Deserialize JSON Array that have different types using Jackson

I have an Android application that uses Jackson to deserialize the data and I face troubles in creating the pojo for this json string:

{
    "response": [{
        "view": "ticker",
        "items": []
    }, {
        "view": "note",
        "note": "This is a note"
    }, {
        "wn": "bla",
        "sd": "bla bla",
        "tf": 28,
        "rh": 22,
        "ws": 9,
        "ti": "14:00",
        "view": "hbhi"
    }]
}

I create the following pojos:

TickerModel.java

public class TickerModel implements Serializable {

@JsonProperty("view")
private String view ;

@JsonProperty("items")
private String items;


public String getView() {
    return view;
}

public void setView(String view) {
    this.view = view;
}

public String getItems() {
    return items;
}

public void setItems(String items) {
    this.items = items;
}

}

NoteModel.java

public class NoteModel implements Serializable {

@JsonProperty("view")
private String view ;

@JsonProperty("note")
private String note;

public String getView() {
    return view;
}

public void setView(String view) {
    this.view = view;
}

public String getNote() {
    return note;
}

public void setNote(String note) {
    this.note = note;
}

}

any ideas on how to to do deserialize this JSON using Jackson?

first validate json using this .

And create pojo classes using this or this

No need to create two separate pojo's, you can have pojo like below -

public class Response {

@JsonProperty("view")
private String view;
@JsonProperty("items")
private List<Object> items = new ArrayList<Object>();
@JsonProperty("note")
private String note;
@JsonProperty("wn")
private String wn;
@JsonProperty("sd")
private String sd;
@JsonProperty("tf")
private Integer tf;
@JsonProperty("rh")
private Integer rh;
@JsonProperty("ws")
private Integer ws;
@JsonProperty("ti")
private String ti;
//setters //getters 
}

Note: Since items is an array in your json, you should map it with array-list of type objects. Also you can get pojo's craeted online if you have json data - http://www.jsonschema2pojo.org/

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