在Retrofit android中解析JSON

时间:2016-12-12 08:13:24

标签: android json parsing retrofit

我正在尝试使用Android上的Retrofit解析以下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;
}
}

3 个答案:

答案 0 :(得分:0)

尝试使用此功能,因为您没有提供&#34; Payload&#34; o bject

 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

    }
});

答案 1 :(得分:0)

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)的原因。如果数组中有多个元素,则需要使用循环然后获取值,对于品牌 subProduct 数组也是如此。

答案 2 :(得分:0)

您正在尝试获取对象PayLoad,并且您拥有

{
"payload": [
    {
      "name"

这意味着它不是从父级开始的,因此您需要在迭代中将答案保存在列表和字母之类的列表中,您可以使用Response.get(position)<-,而这将成为您的有效负载编号位置,希望对您有帮助