如何在Android中使用GSON在jsonArray中检索jsonObject

时间:2018-11-15 07:38:35

标签: android json gson

我正在从API检索数据并使用GSON访问数据。我有一个来自API的数据数组,并且其中还包含一个对象。

数据示例:

{
    "data": [
        {
            "id": 3,
            "company_id": "1",
            "name_nl": "Showtrap trapreno laminaat Kahlua 2 treden Karwei 42x23x25cm",
            "description": "",
            "name_fr": "=ESCALIER DEMO MELAMINE 2MARCHES===",
            "ean_code": "8711283406329",
            "mbh": "1",
            "msrp": "75",
            "article_code": "00076",
            "article_status": "nazorg",
            "source": "Products",
            "created_at": "2018-09-14 11:43:57",
            "updated_at": "2018-09-14 11:43:57",
            "company": {
                "id": 1,
                "name": "JEWE",
                "franco_amount_product": "1500",
                "mail_product": "jewehq@expertmedia.be",
                "status": "A",
                "created_at": "2018-07-06 04:06:08",
                "updated_at": "2018-10-23 14:07:59"
            }
        }

      ]
}

我从JSON生成了Plain Old Java Objects,并得到了2个文件 datum.java ,其中包含数据数组的所有字段,除了 company 对象中的字段。还有一个 Company.java ,其中包含 Company 对象的所有字段。

我在datum.java中有一种方法可以访问Company对象,即

public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

Company.java

@SerializedName("name")
    @Expose
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

像这样我创建了我的模型。我可以获取数据数组的所有字段,但无法理解如何使用GSON从数据数组访问公司对象。

GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("M/d/yy hh:mm a");
        gson = gsonBuilder.create();


   JSONArray jsonArray = response.getJSONArray("data");

                            if (jsonArray.length() > 0) {

                                List<Datum> datumArrayList = new ArrayList<>();

                                datumArrayList = Arrays.asList(gson.fromJson(jsonArray.toString(), Datum[].class));

                                Log.e("TAG", "onResponse:datumArrayList "+datumArrayList.size() );


                                for(Datum datum : datumArrayList){

                                    Log.e("TAG", "onResponse: "+datum.getCompany() );

                                }

我想从公司对象中获得 franco_amount_product 。我如何获得帮助?

//编辑

JSONArray jsonArray = response.getJSONArray("data");

                            if (jsonArray.length() > 0) {

                                List<Datum> datumArrayList = new ArrayList<>();

                                datumArrayList = Arrays.asList(gson.fromJson(jsonArray.toString(), Datum[].class));

                                Log.e("TAG", "onResponse:datumArrayList "+datumArrayList.size() );


                                ProductDetailsModel model = ProductDetailsModel.fromJson("data");

                                model.setData(datumArrayList);

                                for(Datum datum : model.getData()){

                                    Log.e("TAG", "onResponse: " + datum.getCompany().getFrancoAmountProduct() + ""+datum.getEanCode());
                                }

我已经编辑了代码,但现在无法获取任何值。我需要将合并的数据保存到数据库中时如何从数据和公司中访问值

2 个答案:

答案 0 :(得分:0)

您应该为响应创建一个模型类,以处理整个json字符串:

ResponseModel.java

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class ResponseModel {

    @SerializedName("data")
    private List<Datum> data = null;

    public List<Datum> getData() {
        return data;
    }

    public void setData(List<Datum> data) {
        this.data = data;
    }

    public static ResponseModel fromJson(String json) {
        return new Gson().fromJson(json, ResponseModel.class);
    }

}

现在,您可以像下面那样使用它来解析json字符串:

ResponseModel model = ResponseModel.fromJson(jsonString);
// for example for item 0:
String francoAmountProduct = model.getData().get(0).getCompany().getFrancoAmountProduct();

在类似于问题内容的for循环中:

for(Datum datum : model.getData()){
    Log.e("TAG", "onResponse: " + datum.getCompany().getFrancoAmountProduct());
}

答案 1 :(得分:0)

您的Datum.java应该像

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Datum {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("company_id")
    @Expose
    private String companyId;
    @SerializedName("name_nl")
    @Expose
    private String nameNl;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("name_fr")
    @Expose
    private String nameFr;
    @SerializedName("ean_code")
    @Expose
    private String eanCode;
    @SerializedName("mbh")
    @Expose
    private String mbh;
    @SerializedName("msrp")
    @Expose
    private String msrp;
    @SerializedName("article_code")
    @Expose
    private String articleCode;
    @SerializedName("article_status")
    @Expose
    private String articleStatus;
    @SerializedName("source")
    @Expose
    private String source;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("company")
    @Expose
    private Company company;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    public String getNameNl() {
        return nameNl;
    }

    public void setNameNl(String nameNl) {
        this.nameNl = nameNl;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getNameFr() {
        return nameFr;
    }

    public void setNameFr(String nameFr) {
        this.nameFr = nameFr;
    }

    public String getEanCode() {
        return eanCode;
    }

    public void setEanCode(String eanCode) {
        this.eanCode = eanCode;
    }

    public String getMbh() {
        return mbh;
    }

    public void setMbh(String mbh) {
        this.mbh = mbh;
    }

    public String getMsrp() {
        return msrp;
    }

    public void setMsrp(String msrp) {
        this.msrp = msrp;
    }

    public String getArticleCode() {
        return articleCode;
    }

    public void setArticleCode(String articleCode) {
        this.articleCode = articleCode;
    }

    public String getArticleStatus() {
        return articleStatus;
    }

    public void setArticleStatus(String articleStatus) {
        this.articleStatus = articleStatus;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

}

您的Company.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Company {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("franco_amount_product")
    @Expose
    private String francoAmountProduct;
    @SerializedName("mail_product")
    @Expose
    private String mailProduct;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFrancoAmountProduct() {
        return francoAmountProduct;
    }

    public void setFrancoAmountProduct(String francoAmountProduct) {
        this.francoAmountProduct = francoAmountProduct;
    }

    public String getMailProduct() {
        return mailProduct;
    }

    public void setMailProduct(String mailProduct) {
        this.mailProduct = mailProduct;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

}

创建ResponseModel.java

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class ResponseModel {

    @SerializedName("data")
    private List<Datum> data = null;

    public List<Datum> getData() {
        return data;
    }

    public void setData(List<Datum> data) {
        this.data = data;
    }
}

然后按如下所示获取公司对象,

Gson gson = new Gson();
ResponseModel responseModel = gson.fromJson(jsonStr,ResponseModel.class);
for (int i=0;i<responseModel.getData().size();i++){
   Company company = responseModel.getData().get(i).getCompany();
}