简体   繁体   English

Android,使用Jackson来反序列化具有不同类型的JSON数组

[英]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: 我有一个使用Jackson来反序列化数据的Android应用程序,在为此json字符串创建pojo时遇到了麻烦:

{
    "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: 我创建以下pojos:

TickerModel.java 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 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? 关于如何使用杰克逊反序列化此JSON的任何想法?

first validate json using this . 首先使用this验证json。

And create pojo classes using this or this 并使用thisthis创建pojo类

No need to create two separate pojo's, you can have pojo like below - 无需创建两个单独的pojo,您可以像下面这样创建pojo-

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. 注意:由于items是json中的数组,因此应使用类型对象的array-list映射它。 Also you can get pojo's craeted online if you have json data - http://www.jsonschema2pojo.org/ 如果您拥有json数据,也可以在线获取pojo的信息-http: //www.jsonschema2pojo.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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