Amanda
Amanda

Reputation: 58

Android Volley Array in JSON

I have this kind of JSON response

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

And I am able to parse country, country_id, and currency without a problem, problem starts with the product list when I am trying to parse it! below the code

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

And here is my Tarif and Other Class

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

I want to fill the product_list in Tarif class where only one parameter accept and show them in recycler_view

Upvotes: 0

Views: 86

Answers (1)

JunaidKhan
JunaidKhan

Reputation: 744

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

You can see that product_list is JSON Array of string values. But you are converting it into list of Tarif type. It should be converted into list of string type.

Either set values of Tarif as custom objects to JSON Array or change your list type to string.

It should be like this:

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

Tarifs Class

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

Here you go!

Upvotes: 1

Related Questions