gson解析未知类型属性android

gson解析未知类型属性android,android,json,gson,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", imag

在我的应用程序中,我需要解析一个类。。我正在使用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的结构,所以我想将其存储为字符串。如何使用gson将_sourcejson对象存储为字符串我不知道_source的结构是什么意思?你有源代码的结构。它是一个对象,因此您必须创建另一个类,在其中定义源属性,并在Showcase类中访问它:

Source.class

展示类

现在我已经更好地了解了您的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文件中会出现一个新属性,它的解析将在该行停止。

源属性会随着每个属性的变化而变化requests@user1992200:每个请求的_源属性都在变化:在这种情况下,这是一个非常糟糕的OO设计。@user1992200难道你不能问是谁实现了这个json结构来使用吗每次都使用相同的属性,并在不使用时将其设置为null?因为gson库还允许解析不完整的对象,例如,您还可以解析没有category属性的对象。但是您不能解析比类中属性更多的json。我建议您更改json结构或创建一个包含所有属性的类,以便在收到的对象中没有这些属性的情况下,gson库会自动将它们设置为null。@Fondesa yeah。。动态更改属性将导致问题。。在我的应用程序中,xxx_url是用于获取_sourceobjects类型的键。因此,我不解析_sourcejsonobject,而是将其存储为字符串…afetr获取xxx_url类型,使用适当的模型类解析_source
public class Showcase{
    Source _source;
    String image_url;
    String xxx_url;
}
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
    }
}