简体   繁体   English

如何使用Gson解析相同字段但不同类型的JSON

[英]how to use Gson to resolve the same field but different types of JSON

 { "contents": [ { "type": "image", "data": {//data at here is Object "attachment": "picurl", "width": 600, "height": 398 } }, { "type": "text", "data": "聊过往,聊里"//data at here is String type } ] } 

how can i make the class to express this json with gson? 我怎样才能使该类用gson表示这个json?

i try to make the class to express it but fail. 我试图让班级表达它,但失败了。

please follow below structure code . 请遵循以下结构代码。 change datatype according to structure 根据结构更改数据类型

package Trans;

import java.util.List;

public class Demo {

    List<Contents> contentsList;
    String type;
    String data;
    public List<Contents> getContentsList() {
        return contentsList;
    }
    public void setContentsList(List<Contents> contentsList) {
        this.contentsList = contentsList;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getData() {
        return data;
    }
    public void setData(String data) {
        this.data = data;
    }


}

class Data
{
    String attachment;
    int height;
    int width;

    public String getAttachment() {
        return attachment;
    }
    public void setAttachment(String attachment) {
        this.attachment = attachment;
    }
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
    public int getWidth() {
        return width;
    }
    public void setWidth(int width) {
        this.width = width;
    }


}

class Contents
{
    String type;
    List<Data> dataList;

    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public List<Data> getDataList() {
        return dataList;
    }
    public void setDataList(List<Data> dataList) {
        this.dataList = dataList;
    }
}

This tool may be of some help to you 该工具可能对您有所帮助

http://www.jsonschema2pojo.org/ http://www.jsonschema2pojo.org/

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

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