gson解析未知类型属性android

时间:2015-03-30 08:29:43

标签: android json gson

在我的应用程序中我需要解析一个类..我正在使用gson进行解析。结构是

public class Showcase implements Serializable{

public String xxx_url;
public String image_url;
public String _source;}

json结构是:`

[{
_source: {
FlyerID: "infly7",
category: "Electronics and home appliances",
image_url: "xxx.jpg",
issuer: "elica",
issuer_type: "brand",
original_image_url: "yyy.jpg",
thumbnail_image_url: "xxx_yyy.jpg",
valid_from: "2014-12-06",
valid_until: "2015-01-06"
},
image_url: "ccc.jpg",
xxx_url: "ddd"
}
{
_source: {
BOGO: null,
cashback: null,
category: "Mobiles and tablets",
color_code: "cbbdca",
discount_percentage: null,
discount_type: null,
fp_type: null,
image_url: "xxx.jpg",
issuer: "JBL",
product_classification: [
"Speaker"
],
title: "JBL Bt Speaker"
},
image_url: "xxx.jpg",
xxx_url: "eeee"
}]`

我不知道_source的结构所以我想将它存储为string.how,以使用gson将the_source json对象存储为字符串

1 个答案:

答案 0 :(得分:0)

"我不知道_source"的结构。意思?你有源的结构。它是一个对象,所以你必须创建另一个类来定义_source属性,你将在Showcase类中访问它:

<强> Source.class

public class Source {
    String FlyerID;
    String category;
    String image_url;
    String issuer;

    // do also the other properties

    public Source (String FlyerID, String category){  //do the same for the other properties
        this.FlyerID = FlyerID;
        this.category = category;
        //other assignment
    }
}

<强> Showcase.class

public class Showcase{
    Source _source;
    String image_url;
    String xxx_url;
}

现在我已经看到了更好的json源代码,因此我在评论中写道,我建议更改json资源(如果可以的话)因为每次都有不同的属性进行糟糕的解析。 如果您不能使用源类中的所有变量,如果未使用该属性,则将设置为null:

public class Source {
    String FlyerID;
    String BOGO;
    String category;
    String cashback;
    String image_url;
    String color_code;
    String issuer;

    // do also the other properties

    public Source (String FlyerID, String category){  //do the same for the other properties
        this.FlyerID = FlyerID;
        this.category = category;
        //other assignment
    }
}

但是,这是第三次,这不是正确的方法。因为如果你说属性每次都在变化,也许以后新的属性可以出现在json文件中,并且它的解析将在那一行停止。

相关问题