如何从REST端点解析JSON对象?

时间:2018-01-12 01:04:37

标签: java json rest parsing endpoint

我想从端点解析一个JSON对象(这里这个:https://api.coinmarketcap.com/v1/ticker/bitcoin/)并将值存储在特定属性的变量中,在这种情况下是名称。

这是我得到的错误:

java.lang.IllegalStateException:预期名称但是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();
            }

        }
    });

2 个答案:

答案 0 :(得分:0)

您可以将InputStream转换为String,然后从该字符串创建JSONArray。像

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

这样您就不必手动构建阵列。 对JSONArray使用此depandency https://mvnrepository.com/artifact/org.json/json

答案 1 :(得分:0)

您可以使用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;
    }
    ..........
}