在改造android中解析json?

31moq8wy  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(427)

我试图在android上使用改型来解析以下json结构。

{
    "payload": [
        {
          "name": "Rice",
          "brands": [
            {
              "name": "Dawat",
              "subProducts": [
                {
                  "id": 1,
                  "name": "Basmati Long Grain",
                  "creditDays": 20,
                  "currency": "$",
                  "willDeliver": false,
                  "minPrice": 250,
                  "maxPrice": 400,
                  "sku": "1Kg",
                  "uom": ""
                }
              ]
            }
          ]
        }
      ],
      "messages": []
    }

我用电脑制作模型http://www.jsonschema2pojo.org/. 我特别关注的关键是有效负载-->名称、品牌-->名称和子产品-->名称。下面是我到目前为止所做的尝试。有人能帮忙吗?我无法使用改型解析这个json结构

productDetails.enqueue(new Callback<GetProductDetailsByPhoneNumber>() {
        @Override
        public void onResponse(Call<GetProductDetailsByPhoneNumber> call, Response<GetProductDetailsByPhoneNumber> response) {
            Toast.makeText(getApplicationContext(), "Response mil gaya", Toast.LENGTH_LONG);
            List<Payload> subProducts = new ArrayList<Payload>(response.body().payload);
        }

        @Override
        public void onFailure(Call<GetProductDetailsByPhoneNumber> call, Throwable t) {

        }
    });

接口:

@GET("wholesaler/getProductDetailsByPhoneNumber")
Call<GetProductDetailsByPhoneNumber> getProducts(@Query("phoneNumber") String number);

getdservice()

public API getDService(){
    /**
     * The Retrofit class generates an implementation of the API interface.
     */
    if(service == null){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        service = retrofit.create(API.class);
    }
    return service;
}

payload.java

public class Payload {

public String name;
public List<Brand> brands;

public String getName() {
    return name;
}

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

public List<Brand> getBrands() {
    return brands;
}

public void setBrands(List<Brand> brands) {
    this.brands = brands;
}
}
gopyfrb3

gopyfrb31#

尝试使用此选项,因为您没有提供“有效负载”对象

productDetails.enqueue(new Callback<JsonObject>() {
    @Override
    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

      if(response.body()!=null{
         JsonObject jsonObject=response.body();
         if(response.code() == 200){
            if(jsonObject.has("payload"){
              JsonArray dataArray = jsonObject.getAsJsonArray(HAS_DATA);
              if (dataArray.size() > 0) {
                Toast.makeText(getApplicationContext(), "Response Called", Toast.LENGTH_LONG);

                 //your further code

              }
            }
         }
      }

    }

    @Override
    public void onFailure(Call<JsonObject> call, Throwable t) {

     //logic for if response fails

    }
});
zf9nrax1

zf9nrax12#

在onresponse中使用以下代码:

if(response.code()==HttpsURLConnection.HTTP_OK) {   //HttpOk is the response code for 200
    if (response.body() != null) {
        if (response.body().payload!= null) {
            //data is there in an array of type payload
            //save all the data there
            //like you want the name, you can get that by response.body().payload.name and you will get "rice"
            //similarly if you want the name which is in subproducts array use : response.body().payload.get(0).brands.get(0).subProducts.get(0).name and you
            //  will get "Basmati Long Grain" 
        }
    }
}

代码将帮助您反序列化json中的所有数据,并且您可以将其存储在任何需要的地方。另外,我还建议您检查其他响应代码(如400表示错误请求,500表示内部服务器错误等)。看这里,你的有效载荷在一个数组中,其中只有一个元素,这就是为什么我使用 payload.get(0) . 如果数组中有多个元素,则需要使用循环,然后获取值,品牌和子产品数组也是如此。

aoyhnmkz

aoyhnmkz3#

您正在尝试获取一个对象有效负载,并且

{
"payload": [
    {
      "name"

这意味着它不是从父级开始的,所以您需要在迭代中使用response.get(position)<--这将是您的有效载荷编号位置,我希望这可以帮助您

相关问题