Android Массив залпов в JSON - PullRequest
0 голосов
/ 19 марта 2020

У меня есть такой JSON ответ

{"error":false,"country":"United Kingdom","country_id":"903",
"currency":"GBP","product_list":["5","10","15","20","25","30","40","50"]}

И я могу без проблем проанализировать страну, country_id и валюту, проблема начинается со списка продуктов, когда я пытаюсь его проанализировать ! ниже кода

                try {
                    boolean error = response.getBoolean("error");
                if (!error){ 
                    String country = response.getString("country");
                    int country_id = response.getInt("country_id");
                    String currency = response.getString("currency");
                    List<Tarif> tarifs = new 
                    Gson().fromJson(response.getJSONArray("product_list").toString(), new 
                    TypeToken<List<Tarif>>(){}.getType());
                    new DtoneTarifs(country, country_id, currency, tarifs);
                 }
            }

А вот мой класс Tarif и Other

public class  Tarifs {
public String country;
public int country_id;
public String currency;
public List<Tarif> tarifList;

public Tarifs (String country, int country_id, String currency, List<Tarif> tarif){
    this.country = country;
    this.country_id = country_id;
    this.currency = currency;
    this.tarifList = tarif;
}
}

Я хочу заполнить список product_list в классе Tarif, где только один параметр принимает и отображать их в recycler_view

1 Ответ

1 голос
/ 19 марта 2020
{"error":false,"country":"United Kingdom","country_id":"903",
"currency":"GBP","product_list":["5","10","15","20","25","30","40","50"]}

Вы можете видеть, что product_list равен JSON Массив строковых значений. Но вы конвертируете его в список типа Тариф. Он должен быть преобразован в список строкового типа.

Либо установите значения Tarif в качестве пользовательских объектов на JSON Массив, либо измените тип списка на строку.

Это должно быть так:

try {
      boolean error = response.getBoolean("error");
      if (!error){ 
         String country = response.getString("country");
         int country_id = response.getInt("country_id");
         String currency = response.getString("currency");
         List<String> tarifs = new 
         Gson().fromJson(response.getJSONArray("product_list").toString(), new 
                    TypeToken<List<String>>(){}.getType());
         Tarifs result = new Tarifs(country, country_id, currency, tarifs);
       }
 }

Класс тарифов

public class  Tarifs {
public String country;
public int country_id;
public String currency;
public List<String> tarifList;

public Tarifs (String country, int country_id, String currency, List<String> tarif){
    this.country = country;
    this.country_id = country_id;
    this.currency = currency;
    this.tarifList = tarif;
}
}

Вот вам go!

...