使用Retrofit解析动态未知命名数组Json

时间:2018-10-31 11:01:51

标签: android json retrofit

我是新手,下面是json

 {
  "response": "success",
  "servicecode": "134",
  "forecast": {
    "month": {
      "jan": [
        {
          "id": "1",
          "price": "12",
          "Product": "1086",
          "Qty": "14",
          "date": "2018-10-27 16:08:57"
        },
        {
          "id": "2",
          "price": "19",
          "Product": "1746",
          "Qty": "45",
          "date": "2018-10-27 16:08:57"
        }
      ],
      "april": [
        {
          "id": "3",
          "price": "89",
          "Product": "1986",
          "Qty": "15",
          "date": "2018-10-27 16:08:57"
        },
        {
          "id": "1",
          "price": "12",
          "Product": "1086",
          "Qty": "145",
          "date": "2018-10-27 16:08:57"
        }
      ],
      "jun": [
        {
          "id": "81",
          "price": "132",
          "Product": "17086",
          "Qty": "1445",
          "date": "2018-10-27 16:08:57"
        },
        {
          "id": "11",
          "price": "132",
          "Product": "10786",
          "Qty": "1445",
          "date": "2018-10-27 16:08:57"
        }
      ]
    }
  },
  "message": "Competitor Sales."
}

在这里,那些月份(1月,4月,6月)是动态的(可能会到来,或者不会),因此如何使用改型来解析它。 我不知道如何创建我的模型类。 我的问题看起来像this,但这里没有更多细节。 告诉我一个更好的教程。

下面的模型类

class ForecastViewModel {
    @SerializedName("forecast")
    Forecast[] data;

    public Forecast[] getData() { return data; }

    private class Forecast {
        @SerializedName("month")
        MonthData[] month;

        public MonthData[] getMonth() { return month; }

        private class MonthData {
            private Map<String, Pojo> forecastdata = new HashMap<>();

            private class Pojo {

                @SerializedName("id")
                @Expose
                private String pID;
                @SerializedName("price")
                @Expose
                private String pPrice;
                @SerializedName("Product")
                @Expose
                private String pProduct;
                @SerializedName("Qty")
                @Expose
                private String pQty;
                @SerializedName("date")
                @Expose
                private String pDate;

                public String getpID() {
                    return pID;
                }
                public void setpID(String pID) {
                    this.pID = pID;
                }
                public String getpPrice() {
                    return pPrice;
                }
                public void setpPrice(String pPrice) {
                    this.pPrice = pPrice;
                }
                public String getpProduct() {
                    return pProduct;
                }
                public void setpProduct(String pProduct) {
                    this.pProduct = pProduct;
                }
                public String getpQty() {
                    return pQty;
                }
                public void setpQty(String pQty) {
                    this.pQty = pQty;
                }
                public String getpDate() {
                    return pDate;
                }
                public void setpDate(String pDate) {
                    this.pDate = pDate;
                }
            }
            }
    }
}

... !!

2 个答案:

答案 0 :(得分:0)

method 1 - without using model class

假设您的“月”对象是jsonObjectResponse。您可以使用Iterator

    JSONObject jsonResponse = new JSONObject(jsonObjectResponse);
Iterator  iteratorObj = jsonResponse.keys();
while (iteratorObj.hasNext())
     {
       JSONArray monthArray=(JSONArray)iteratorObj.next()
       //add all monthArray to an arraylist
     }

**为模型类编辑**

method 2 - using model class

您可以使用Map<String, List<MonthModel>>来获得month的动态响应

您有两个创建三个这样的模型分类:

Example.java

public class Example {
@SerializedName("response")
@Expose
private String response;
@SerializedName("servicecode")
@Expose
private String servicecode;
@SerializedName("forecast")
@Expose
private Forecast forecast;
@SerializedName("message")
@Expose
private String message;

public String getResponse() {
    return response;
}

public void setResponse(String response) {
    this.response = response;
}

public String getServicecode() {
    return servicecode;
}

public void setServicecode(String servicecode) {
    this.servicecode = servicecode;
}

public Forecast getForecast() {
    return forecast;
}

public void setForecast(Forecast forecast) {
    this.forecast = forecast;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}
}

Forecast.java

public class Forecast {
@SerializedName("month")
@Expose
private Map<String, List<MonthModel>> result;

public Map<String, List<MonthModel>> getResult() {
    return result;
}

public void setResult(Map<String, List<MonthModel>> result) {
    this.result = result;
}
}

MonthModel.java

public class MonthModel {
@SerializedName("id")
@Expose
private String id;
@SerializedName("price")
@Expose
private String price;
@SerializedName("Product")
@Expose
private String product;
@SerializedName("Qty")
@Expose
private String qty;
@SerializedName("date")
@Expose
private String date;

public String getId() {
    return id;
}

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

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

public String getProduct() {
    return product;
}

public void setProduct(String product) {
    this.product = product;
}

public String getQty() {
    return qty;
}

public void setQty(String qty) {
    this.qty = qty;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}
}

现在执行如下所示的改造呼叫

private void getMonthData() {
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();
    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl("add_base_url")
            .build();
    RequestInterface requestInterface = retrofit.create(RequestInterface.class);
    Call<Example> call = requestInterface.getMonths();
    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {
            Map<String, List<MonthModel>> resultMap=response.body().getForecast().getResult();
            Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<Example> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
        }
    });
}

RequestInterface.java

public interface RequestInterface {
@GET("add_your_url_endpoint")
Call<Example> getMonths();
}

答案 1 :(得分:0)

我会使用Gson lib使用自定义Json适配器来实现。因此,您将不必触摸数据结构(如果无论如何也不能这样做),也无需添加无限键555。

https://www.tutorialspoint.com/how-to-implement-custom-jsonadapter-using-gson-in-java