Home How to Parse JSON object from a REST ENDPOINT?
Reply: 2

How to Parse JSON object from a REST ENDPOINT?

Pasoon
1#
Pasoon Published in 2018-01-12 01:04:37Z

I want to parse a JSON object from an endpoint (this one here: https://api.coinmarketcap.com/v1/ticker/bitcoin/) and store the value in a variable at a specific attribute, which in this case is the name.

This the ERROR i get:

java.lang.IllegalStateException: Expected a name but was STRING...

AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            // All your networking logic
            // should be here

            try {
                String u = "https://api.coinmarketcap.com/v1/ticker/bitcoin";
                URL coinMarketCapApi = new URL(u);

                HttpsURLConnection myConnection = (HttpsURLConnection) coinMarketCapApi.openConnection();
                myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");

                if (myConnection.getResponseCode() == 200) {
                    // Success
                    InputStream responseBody = myConnection.getInputStream();

                    InputStreamReader responseBodyReader =
                            new InputStreamReader(responseBody, "UTF-8");
                    JsonReader jsonReader = new JsonReader(responseBodyReader);

                    jsonReader.beginArray();

                    while (jsonReader.hasNext()) {

                        String key = jsonReader.nextName();

                        if (key.equals("name")) {        
                            String value = jsonReader.nextName();


                            break; // Break out of the loop
                        } else {
                            jsonReader.skipValue();
                        }
                    }

                    jsonReader.close();
                    myConnection.disconnect();
                } else {
                    // Error handling code goes here
                }

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

        }
    });
maneesh
2#
maneesh Reply to 2018-01-12 03:02:23Z

you can convert the InputStream to String and then Create JSONArray from that string. like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
JSONArray jsonarray = new JSONArray(theString);

This way you don't have to manually construct the array. Use this depandency for JSONArray https://mvnrepository.com/artifact/org.json/json

Woocheol Park
3#
Woocheol Park Reply to 2018-01-13 04:10:18Z

You can fix the problem using gson.

https://github.com/google/gson

 com.google.gson.stream.JsonReader jsonReader =
            new com.google.gson.stream.JsonReader(new InputStreamReader(responseBody));

    ArrayList<Coin> coins = new Gson().fromJson(jsonReader, Coin.class);

    coins.forEach(coin -> System.out.println(coin.name));

public class Coin{

    private String id;
    private String name;
    private String symbol;
    private int rank;
    @SerializedName("price_usd")
    private double priceUsd;
    ...........

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSymbol() {
        return symbol;
    }

    public int getRank() {
        return rank;
    }

    public double getPriceUsd() {
        return priceUsd;
    }
    ..........
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.35935 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO