【问题标题】:How to Parse JSON object from a REST ENDPOINT?如何从 REST 端点解析 JSON 对象?
【发布时间】:2018-01-12 01:04:37
【问题描述】:

我想从一个端点解析一个 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();
            }

        }
    });

【问题讨论】:

    标签: java json rest parsing endpoint


    【解决方案1】:

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

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

    这样你就不必手动构造数组了。 将此依赖项用于 JSONArray https://mvnrepository.com/artifact/org.json/json

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我一直在研究它,但我似乎明白了。我需要一个类似于我的示例,其中用户向端点发送请求并使用 GSON 对其进行解析,然后例如打印出其中一个属性。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多