【问题标题】:Get JSON from URL and create JSON Object从 URL 获取 JSON 并创建 JSON 对象
【发布时间】:2016-05-14 00:06:07
【问题描述】:

我正在使用异步任务 + HttpURLConnection 在 Android 中获取 this JSON。我正在尝试用 JSONObject 解析它。这是我的班级:

public class getData extends AsyncTask<String, String, String> {
        HttpURLConnection urlConnection;
        @Override
        protected String doInBackground(String... args) {
            StringBuilder result = new StringBuilder();
            try {
                URL url = new URL("http://bitcoinstats.azurewebsites.net/api/ExchangeVolume");
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            }catch( Exception e) {
                e.printStackTrace();
            }
            finally {
                urlConnection.disconnect();
            }
            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {

            //Do something with the JSON string
            //result = result.replace("\\", "");
            try {
                JSONObject json = new JSONObject(result);
                tv.setText("Converted");
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(),
                        "Error converting to json", Toast.LENGTH_SHORT)
                        .show();
                tv.setText(result);
                e.printStackTrace();
            }
            //tv.setText(result);
        }

    }

观察:tv 是我页面的 texview,我在其上打印结果。

我的问题是 JSONException 被抛出,我不知道为什么。 JSON 是有效的,我签入了 http://jsonlint.com/ ,并且我正确接收了 json,因为我可以在 TextViewer 中完美地打印它。那么,为什么这种从 String 简单地创建 JSONObject 不起作用呢?

【问题讨论】:

  • 你能用e.printStackTrace();的输出更新你的问题吗?
  • 您的 json 包含不需要的标签 schemas.microsoft.com/2003/10/Serialization" >& 尝试从服务器端删除。
  • 在点击这个请求后得到 xml 响应而不是纯 json 包含上面提到的标签 bitcoinstats.azurewebsites.net/api/ExchangeVolume
  • 你能试试 UTF-8 - new BufferedReader(new InputStreamReader(in, "UTF-8"))吗?
  • @itechevo 刚刚尝试过,同样的错误..

标签: android json urlconnection


【解决方案1】:

您的回复在&lt;String&gt; &lt;/String&gt; 范围内。因此,您必须删除&lt;String&gt; &lt;/String&gt;,然后照常进行。

result = result.replaceAll("<string>", "");
result = result.replaceAll("</string>", "");

现在

JSONObject json = new JSONObject(result);

希望这对你有用

【讨论】:

    【解决方案2】:

    我使用 Microsoft Azure 托管向我发送所需 JSON 的 API。代码是用 C# 编写的,奇怪的是,返回 JSON 对象的“toString()”并尝试在我的 Android 应用程序中使用它是不可能的,代码中出现了一些奇怪的东西。无论如何,我的一个朋友,告诉我如何正确返回值。

    基本上我用“HttpResponseMessage”替换了return的类型,上面的java代码可以正常工作。

    【讨论】:

      【解决方案3】:

      试试这个:

      @Override
              protected void onPostExecute(String result) {
      
      //it  first replace \ & after that extra " from result.
      
                  result= result.replace("\\",""); 
                  result = result.replaceFirst("\"","");
      
                  Log.d("Test","Result:"+result);
                  //Do something with the JSON string
                  //result = result.replace("\\", "");
                  try {
                      JSONObject json = new JSONObject(result);
                      Log.d("Test",json.toString());
          //            tv.setText("Converted");
                  } catch (JSONException e) {
          //            Toast.makeText(getApplicationContext(),
          //                    "Error converting to json", Toast.LENGTH_SHORT)
          //                    .show();
          //            tv.setText(result);
                      e.printStackTrace();
                  }
                  //tv.setText(result);
              }
      

      【讨论】:

      • 这将根据需要为您提供正确的 Json。为此,我们需要应用字符串替换函数。
      【解决方案4】:

      响应在JSON 周围包含一个&lt;string&gt; 标记。我们可以使用Pattern 类通过正则表达式匹配来删除它。然后将其转换为JSONObject

      试试这个,

      @Override
      protected void onPostExecute(String result) {
          try {
              Pattern sPattern = Pattern.compile("<string xmlns=\".*\">(.*)<\\/string>");
              Matcher m = sPattern.matcher(result);
              if (m.find()) {
                  result = m.group(1);
              }
              JSONObject json = new JSONObject(result);
              result = json.getString("timestamp");
              tv.setText(result);
          } catch (JSONException e) {
              Toast.makeText(getApplicationContext(),
                      "Error converting to json", Toast.LENGTH_SHORT)
                      .show();
              tv.setText(result);
              e.printStackTrace();
          }
      }
      

      【讨论】:

        【解决方案5】:

        这对你也有帮助。

        How to automate login a website

        【讨论】:

          【解决方案6】:

          您得到的结果是 XML 格式的。 所以必须先解析xml,再解析json对象。

          String response = response_from_URL
          response = response.replaceAll("<string>", "");
          response = response.replaceAll("</string>", "");
          

          【讨论】:

          • 我不知道为什么,当你用浏览器打开时,有那个花哨的微软 XML,但我在 App 中打印并没有 XML,只有 JSON。
          • 对不起?你是什​​么意思?答案是一样的。
          【解决方案7】:

          也许“结果”的格式不正确?

          查看此示例:String to jsonobject in java

          【讨论】:

            猜你喜欢
            • 2013-03-15
            • 1970-01-01
            • 2020-05-11
            • 2021-07-05
            • 2016-12-25
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多