Разбор динамического неизвестного именованного массива Json с помощью Retrofit - PullRequest
0 голосов
/ 31 октября 2018

Я новичок в модернизации, ниже 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."
}

здесь, эти месяцы (январь, апрель, июнь) являются динамическими (они могут прийти или не будут), так как разобрать это с помощью модернизации. я понятия не имею, как создать свой модельный класс. моя проблема немного похожа на это , но в этом нет больше деталей. скажите мне лучший учебник для этого.

Класс модели ниже

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;
                }
            }
            }
    }
}

... !!

1 Ответ

0 голосов
/ 31 октября 2018

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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...