繁体   English   中英

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

[英]Android , Deserialize JSON Array that have different types using Jackson

我有一个使用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"
    }]
}

我创建以下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;
}

}

关于如何使用杰克逊反序列化此JSON的任何想法?

首先使用this验证json。

并使用thisthis创建pojo类

无需创建两个单独的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 
}

注意:由于items是json中的数组,因此应使用类型对象的array-list映射它。 如果您拥有json数据,也可以在线获取pojo的信息-http: //www.jsonschema2pojo.org/

暂无
暂无

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

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