【问题标题】:Parsing JSON data from an HTTP connection从 HTTP 连接解析 JSON 数据
【发布时间】:2017-12-14 13:09:35
【问题描述】:

我正在尝试在以下链接中获取键“GBP”的值:https://api.fixer.io/latest

我已成功连接到 API,并且能够循环访问密钥,直到获得“费率”。不过,在找到“英镑”之前,我不知道如何在所有货币中循环。

注意:我正在解析 Json - 我正在努力解析其中包含 Json 的 Json 对象。它与您引用的重复项不同。

到目前为止,我的代码如下所示:

String urlStr = "https://api.fixer.io/latest";

AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
                    // Create URL
                    URL url = null;
                    try {
                        url = new URL(urlStr);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }

                    // Create connection
                    try {
                        HttpURLConnection myConnection =
                                (HttpURLConnection) url.openConnection();

                        if (myConnection.getResponseCode() == 200) {
                            InputStream responseBody = myConnection.getInputStream();
                            InputStreamReader responseBodyReader =
                                    new InputStreamReader(responseBody, "UTF-8");
                            JsonReader jsonReader = new JsonReader(responseBodyReader);

                            jsonReader.beginObject(); // Start processing the JSON object
                            while (jsonReader.hasNext()) { // Loop through all keys
                                String key = jsonReader.nextName(); // Fetch the next key
                                if (key.equals("rates")) { // Check if desired key
                                    // Fetch the value as a String
                                    String value = jsonReader.nextString();

                                    //currentCurrency = value;

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

                        } else {
                            // Error handling code goes here
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

【问题讨论】:

标签: android json http


【解决方案1】:

试试这个

JSONObject jsonObject = new JSONObject(" your json response ");


    Iterator iteratorObj = jsonObject.keys();
    while (iteratorObj.hasNext())
    {
        String JsonObjRates = (String)iteratorObj.next();

        if (JsonObjRates.equals("rates")) {

            JSONObject jo_rates = jsonObject.getJSONObject(JsonObjRates);

            Iterator<String> keys = jo_rates.keys();
            while (keys.hasNext())
            {
                String key = keys.next();
                String value = jo_rates.getString(key);
                Log.i("RATES key", key);
                Log.i("RATES value", value);

                if(key.equals("GBP"))
                {
                        Log.i("GBP RATES key", key);
                        Log.i("GBP RATES value", value);
                }
            }

        }

    }

输出

【讨论】:

  • @Jamles 请用输出检查我的答案。
  • 这看起来很棒。我还没有让它工作,因为我需要创建一个 JSONObject 而我没有在上面这样做。我将更改我拥有的内容并使用您的解决方案,因为它不需要任何额外的依赖项。谢谢你
【解决方案2】:

而不是使用下面使用的手动解析。

请在 Android Studio 中使用 RoboPojo 生成器,它将帮助您为您创建模型类并直接将 setData 设置为您的模型类。

如果你使用 Gson 来设置数据。

下面的 ilink 对你有帮助:

https://github.com/robohorse/RoboPOJOGenerator

希望对你有所帮助。

【讨论】:

    【解决方案3】:

    您可以使用 Volleylibrary 来请求该网址,您将得到响应。 通过相关url获取响应后,您可以在Android Studio上进行解析。

    dependencies {
        ...
        compile 'com.android.volley:volley:1.1.0'
    }
    

    以上将添加到依赖项中。

    以下将添加到您的 Activity(如 MainActivity)中。

     String url ="https://api.fixer.io/latest";
    
    
    
         // Request a string response from the provided URL.
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                        new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject resultJSON=new JSONObject(response);
                    JSONObject rates=resultJSON.getJSONObject("rates");
                    string GPB=rates.getString("GPB");
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    mTextView.setText("That didn't work!");
                }
            });
            // Add the request to the RequestQueue.
            queue.add(stringRequest);
    

    我想它会起作用的。反馈是否有效。

    【讨论】:

      【解决方案4】:

      试试这个。

      您必须循环访问 jsonobject,因此首先为费率创建类。

      public Rates readRates(JsonReader reader) throws IOException {
       String country_rate = null;
      
      
       reader.beginObject();
       while (reader.hasNext()) {
         String name = reader.nextName();
         if (name.equals("GBP")) {
           country_rate = reader.nextString();
         } else {
           reader.skipValue();
         }
       }
       reader.endObject();
       return new Rates(country_rate);
      

      }

      在这个 http 方法开始时标记你的类

      Rates rate = null;
      

      替换此代码

      if (key.equals("rates")) { // Check if desired key
                                      // Fetch the value as a String
                                      String value = jsonReader.nextString();
      
                                      //currentCurrency = value;
      
                                      break; // Break out of the loop
                                  } else {
                                      jsonReader.skipValue(); // Skip values of other keys
                                  }
      

      有了这个

      if (key.equals("rates"))
      {
         rate = readRates(jsonReader);
         String rate_value = rate.country_rate;
      }
      else 
      {
            jsonReader.skipValue(); // Skip values of other keys
       }
      

      更多详情https://developer.android.com/reference/android/util/JsonReader.html

      希望对你有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多