【问题标题】:Facing Error in "getJSONFromUrl" in AndroidAndroid 中的“getJSONFromUrl”面临错误
【发布时间】:2015-09-22 08:17:15
【问题描述】:

我遇到了getJSONFromUrl() 的问题,即使我已经添加了库。我从 [这里] 得到的。(http://www.findjar.com/jar/com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar.html)

下面是我的类,用于从 JSON 格式的 URL 获取数据。

我不确定为什么会出现问题。他们不断显示消息

无法解析getJSONFromUrl方法

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

        final String TAG = "AsyncTaskParseJson.java";

        // set your json string url here
        String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";

        // contacts JSONArray
        JSONArray dataJsonArr = null;

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... arg0) {

            try {

                // instantiate our json parser
                JsonParser jParser = new JsonParser();

                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

                // get the array of users
                dataJsonArr = json.getJSONArray("Users");

                // loop through all users
                for (int i = 0; i < dataJsonArr.length(); i++) {

                    JSONObject c = dataJsonArr.getJSONObject(i);

                    // Storing each json item in variable
                    String firstname = c.getString("firstname");
                    String lastname = c.getString("lastname");
                    String username = c.getString("username");

                    // show the values in our logcat
                    Log.e(TAG, "firstname: " + firstname
                            + ", lastname: " + lastname
                            + ", username: " + username);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {}
    }

因此,我们将不胜感激。

【问题讨论】:

  • 我确实应用了所有这些东西,但仍然无法正常工作。
  • 检查是否在调用 API 时收到响应?你在哪里调用 API 我找不到任何调用 http 方法
  • 试试这个 JSONObject jsonObject = new JSONObject("your response string"); JSONArray jsonArray = jsonObject.getJSONArray("用户");

标签: android json


【解决方案1】:

这里我检查了你也可以用这种方式使用的工作演示。

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    final String TAG = "AsyncTaskParseJson.java";

    // set your json string url here
    String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";

    // contacts JSONArray
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @Override
    protected String doInBackground(String... arg0) {

        try {

            // instantiate our json parser
            //JsonParser jParser = new JsonParser();

            JSONParser jParser = new JSONParser();
            String text = "";
            BufferedReader reader=null;
            try
            {

                // Defined URL  where to send data
                URL url = new URL(yourJsonStringUrl);

                // Send POST data request

                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
               /* OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write( data );
                wr.flush();*/

                // Get the server response

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while((line = reader.readLine()) != null)
                {
                    // Append server response in string
                    sb.append(line + "\n");
                }


                text = sb.toString();
            }
            catch(Exception ex)
            {

            }
            finally
            {
                try
                {

                    reader.close();
                }

                catch(Exception ex) {}
            }


            // get json string from url
            JSONObject json = (JSONObject) jParser.parse(text);


            // get the array of users
            dataJsonArr = (JSONArray) json.get("Users");

            // loop through all users
            for (int i = 0; i < dataJsonArr.size(); i++) {

                JSONObject c = (JSONObject) dataJsonArr.get(i);

                // Storing each json item in variable
                String firstname = (String) c.get("firstname");
                String lastname = (String) c.get("lastname");
                String username = (String) c.get("username");

                // show the values in our logcat
                Log.e(TAG, "firstname: " + firstname
                        + ", lastname: " + lastname
                        + ", username: " + username);

            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String strFromDoInBg) {



    }
}

这里是日志输出

09-22 10:54:49.428  28797-29142/mimg.com.demodrop E/AsyncTaskParseJson.java﹕ firstname: Mike, lastname: Dalisay, username: mike143
09-22 10:54:49.428  28797-29142/mimg.com.demodrop E/AsyncTaskParseJson.java﹕ firstname: Jemski, lastname: Panlilios, username: jemboy09
..................

【讨论】:

  • @Ando Masahashi 感谢您的好评。但我仍然面临 JSONObject json = (JSONObject) jParser.parse(text); 上的错误;
【解决方案2】:

查看 JsonParser 的 source code

这个类没有方法getJSONFromUrl(),所以自然无法解析。

其实这个方法doesn't exist anywhere in the json-simple library

【讨论】:

  • @Tim Castelijns 那么有没有简单的解决方案可以从 URL 获取 Json 结果??
  • @Mediasoft 我看不到。顺便说一句,JsonParser jParser = new JsonParser(); 这个类来自哪里?它是您自己的自定义解析器类吗?如果是这样,请添加代码
【解决方案3】:

您可以编写自己的 JSON 提取器和解析器。

public class MyJsonFetcher{

    public String getJsonString(String url){
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

           inputStream = httpEntity.getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }

       try {
           BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
           StringBuilder sBuilder = new StringBuilder();

           String line = null;
           while ((line = bReader.readLine()) != null) {
               sBuilder.append(line + "\n");
           }

            inputStream.close();
            return sBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject getJsonObject(String json){
        try {
            return new JSONObject(json);    
        } catch (JSONException e) {}
        return null;
    }

}

并像这样使用它:

JSONObject obj = fetcher.getJsonObject(fetcher.getJsonString(my_url));

来自this answer的代码

【讨论】:

  • return new JSONArray(json); 应该是JSONObject(json)
猜你喜欢
  • 1970-01-01
  • 2020-02-21
  • 2016-12-07
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
相关资源
最近更新 更多