簡體   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