Android Application Consuming Webservice

Asked

Viewed 549 times

0

I’m trying to create my first app to make use of a Webservice, in which case I’m just trying to return some of the information via string and later put each piece of information in its proper component, I am trying to use the coinmarketcap API to bring information, but when I try to convert the JSON error : java.util.Concurrent.Executionexception: com.google.gson.Jsonsyntaxexception: java.lang.Illegalstateexception: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ appears, follow my 3 app classes so far:

public class MainActivity extends AppCompatActivity {
//ATRIBUTOS
private Button btOK;
private TextView tvResposta;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btOK = (Button) findViewById(R.id.bt_consultar);
    tvResposta = (TextView) findViewById(R.id.tv_resposta);

    btOK.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //FAZENDO A CONSULTA NO WEBSERVICES
            try{
                Coins coins = new HTTPService().execute().get();
                tvResposta.setText(coins.toString()); //aqui chama a função to string

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    });
}
} 

Model class:

public class Coins {

private String id;
private String name;
private String symbol;
private String rank;
private String price_usd;
private String price_btc;
//private String volume_usd_24h;
private String market_cap_usd;
private String available_supply;
private String total_supply;
private String percent_change_1h;
private String percent_change_24h;
private String percent_change_7d;
private String last_updated;

public String converter(){
    return "id: "+ getId()
            +"\n name: "+ getName()
            +"\n rank: "+ getRank()
            +"\n price_usd: "+ getPrice_usd()
            +"\n price_btc: "+getPrice_btc();
}

Class making the request and connection:

public class HTTPService extends AsyncTask<Void, Void, Coins> {


@Override
protected Coins doInBackground(Void... voids) {
    StringBuilder resposta = new StringBuilder();

    try{
        //URL QUE SERÁ CONSUMIDA
        URL url = new URL("https://api.coinmarketcap.com/v1/ticker/bitcoin/");

        //---- ABRINDO A CONEXÃO ---
        HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
        conexao.setRequestMethod("GET");
        conexao.setRequestProperty("Content-type","application/json");
        conexao.setRequestProperty("Accept", "application/json");
        conexao.setDoOutput(true);
        conexao.setConnectTimeout(5000);
        conexao.connect();

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

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

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //---- convertendo dados do JSON
    return new Gson().fromJson(resposta.toString(), Coins.class);
}

@Override
protected void onPostExecute(Coins coins) {
    super.onPostExecute(coins);
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}

The error is presented when it reaches this line here:

return new Gson().fromJson(resposta.toString(), Coins.class);

Note: I omitted the getters and setters of the model class, but they are all there.

1 answer

0


This happens because the API returns a Json Array and the lib Gson is trying to convert this array, for a object.

That is, for the code to work you must convert to List<Coins> using the TypeToken and then return the object.

class HTTPService extends AsyncTask<Void, Void, Coins> {


    @Override
    protected Coins doInBackground(Void... voids) {
        StringBuilder resposta = new StringBuilder();

        try{
            //URL QUE SERÁ CONSUMIDA
            URL url = new URL("https://api.coinmarketcap.com/v1/ticker/bitcoin/");

            //---- ABRINDO A CONEXÃO ---
            HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
            conexao.setRequestMethod("GET");
            conexao.setRequestProperty("Content-type","application/json");
            conexao.setRequestProperty("Accept", "application/json");
            conexao.setDoOutput(true);
            conexao.setConnectTimeout(5000);
            conexao.connect();

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

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

        } catch (Exception e) {
            e.printStackTrace();
        }

        List<Coins> coins = new Gson().fromJson(resposta.toString(), new TypeToken<List<Coins>>(){}.getType() );

        //---- convertendo dados do JSON
        return coins.size() > 0 ? coins.get(0) : null;
    }
}
  • For the example I needed in string worked perfectly !!! Thank you very much Valdeir Psr!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.