【问题标题】:Android , Deserialize JSON Array that have different types using JacksonAndroid,使用 Jackson 反序列化具有不同类型的 JSON 数组
【发布时间】:2017-03-27 07:11:18
【问题描述】:

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

我创建了以下 pojo:

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;
}

}

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

【问题讨论】:

    标签: java android json serialization jackson


    【解决方案1】:

    不需要创建两个单独的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 中是一个数组,你应该用数组列表类型的对象来映射它。如果你有 json 数据,你也可以在线获取 pojo 的创建 - http://www.jsonschema2pojo.org/

    【讨论】:

      【解决方案2】:

      首先使用 this 验证 json。

      并使用thisthis 创建pojo 类

      【讨论】:

        猜你喜欢
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 2020-07-27
        • 2015-11-02
        • 2021-02-08
        • 2019-06-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多