Converting JSON to arraylist android

1

Good afternoon!    I am trying to consume an API in android but I am having difficulty because in the JSON file it brings a category, I tried to add the variable "acronym" but it did not work; the JSON returned in the variable response is this: This "brl": { , is where I believe it's the information I'm not about to put on the list!

{"brl":{"name":"Real","txWithdrawalFee":9,"MinWithdrawal":30,"txWithdrawalPercentageFee":0.0025,"minConf":1,"minDeposit":0,"txDepositFee":0,"txDepositPercentageFee":0,"minAmountTrade":1,"decimal":8,"decimal_withdrawal":8,"active":1,"dev_active":1,"under_maintenance":0,"order":"010","is_withdrawal_active":1,"is_deposit_active":1},"btc":{"name":"Bitcoin","txWithdrawalMinFee":0.0001,"txWithdrawalFee":0.0001,"MinWithdrawal":0.004,"txWithdrawalPercentageFee":0,"minConf":1,"minDeposit":0,"txDepositFee":0,"txDepositPercentageFee":0,"minAmountTrade":0.0001,"decimal":8,"decimal_withdrawal":8,"active":1,"dev_active":1,"under_maintenance":0,"order":"020","is_withdrawal_active":1,

Follow the variables in my model class:

public class Currencies {
//ATRIBUTOS
private String sigla;
private String name;
private String txWithdrawalFee; //taxa de retirada
private String txWithdrawalPercentageFee; //percentual da taxa de retirada
private String minConf;
private String minAmountTrade; //quantidade minima para trade
private String decimal;
private String active;

Below are the getter and setters methods.

And this is the class that makes the connection

public class HTTPService extends AsyncTask<Void, Void, Currencies> {
//ATRIBUTOS
private ArrayAdapter adapter;
private ListView listView;
private Context context;
private List<Currencies> currenciesList;
private ArrayList<Currencies> currenciesArrayList;
private ProgressBar load;
private int task;
private String call;

private static final String URL_CURRENCIES = "https://braziliex.com/api/v1/public/currencies";

public HTTPService(ArrayList<Currencies> mCurrencies, Context c, int param){
    this.currenciesArrayList = mCurrencies;
    this.context = c;
    this.task = param;
}

@Override
protected Currencies doInBackground(Void... voids) {
    //reposta da chamada da API da Braziliex
    StringBuilder resposta = new StringBuilder();

    //bloco que tenta executar a chamada da API
    try{
        //verificando qual será a chamada
        switch (task){
            case 1:
                call = URL_CURRENCIES;
                break;
        }

        //fazendo a chamada da API
        URL url = new URL("https://braziliex.com/api/v1/public/currencies");

        /**** ABRINDO A CONEXÃO ****/
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setDoOutput(true);
        conn.setConnectTimeout(5000);//tempo maximo tentando conexão
        conn.connect();

        //----- LENDO AS INFORMAÇÕES OBTIDAS -----/
        Scanner scanner = new Scanner(url.openStream());
        currenciesArrayList.clear();

        while (scanner.hasNext()){
            resposta.append(scanner.next());
        }


    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //O ERRO ACONTECE NESSA LINHA, AO PASSAR PARA A LISTA
    currenciesList = new Gson().fromJson(resposta.toString(), new TypeToken<List<Currencies>>(){}.getType());

    return currenciesList.size() > 0 ? currenciesList.get(0) : null;

}

When executing, in the line where I marked that happens the error presents the following exception:

  

Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

The return on the braziliex website:

Thank you!

    
asked by anonymous 21.04.2018 / 22:46

1 answer

0

In fact, the returned JSON is not a list, it is an object with 2 objects inside, btc and ltc . So, instead of converting JSON to a list, you need to identify the ltc object and convert, then identify the btc object and convert as well.

JSONObject respostaJsonObject = new JSONObject(resposta.toString());

JSONObject ltcJsonObject = respostaJsonObject.getJSONObject("ltc"); //Pegando apenas o  
//objeto ltc dentro do json, você pode manusear a classe JSONObject ou fazer 
//como eu fiz abaixo

Currencies ltc = new Gson().fromJson(ltcJsonObject.toString(), Currencies.class);

Currencies btc = new Gson().fromJson(
      respostaJsonObject.getJSONObject("btc").toString(),
      Currencies.class
);
    
22.04.2018 / 02:29