android - JSONObject 解析错误

标签 android json

我正在使用 JSONObject 来解析下载的内容。尽管解析器适用于大多数 json,但它会为特定文件中的 json 抛出异常。

任何关于为什么抛出异常以及如何修复异常的建议将不胜感激。

代码:

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

            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0], parseJson);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {

            // The parsed result comes in here
           // textView.setText(result);


        }

        private String downloadUrl(String URLString, boolean parseJSON) throws IOException { // when parsejson is false, xml will be parsed
            InputStream is = null;
            // Only display the first 500 characters of the retrieved
            // web page content.
            int len = 50000;

            try {
                URL url = new URL(URLString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                if (useUserAuthentication) connection.setRequestProperty ("Authorization", "Basic TjN3czRwcDI0OnJld2R1Y0NvYVF1ZWFyZzk=");
                else connection.setRequestProperty("Authorization", userToken);

                connection.setDoInput(true);
                connection.setRequestMethod(requestType);

                connection.setReadTimeout(10000 /* milliseconds */);
                connection.setConnectTimeout(15000 /* milliseconds */);

                if (postHashMap != null) {

                    connection.setDoOutput(true);
                    String query = getQuery(postHashMap);
                    int contentLength = query.getBytes("UTF-8").length;
                    connection.setFixedLengthStreamingMode(contentLength);

                    OutputStream os = connection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    writer.write(query);
                    writer.close();
                    os.close();
                }


                // Starts the query
                connection.connect();
                int response = connection.getResponseCode();

                Log.i(LOGTAG, "The response is: " + String.valueOf(response));
                is = connection.getInputStream();

                // Convert the InputStream into a string
                String contentAsString = readIt(is, len);

                // CREATE IMAGE FROM INPUT STREAM
                //Bitmap bitmap = BitmapFactory.decodeStream(is);
                //ImageView imageView = (ImageView) findViewById(R.id.image_view);
                //imageView.setImageBitmap(bitmap);

                if (parseJSON) {

                    try {
                        String length = String.valueOf(contentAsString.length());
                        Log.i(LOGTAG, "the length is " +length);
                        //contentAsString = "{\"string\":\"But during winter, it’s more important\"}";
                        //contentAsString.replace("’","'");
                        //contentAsString = "{\"user_id\":\"juan\"}";
                        JSONObject jsonObject = new JSONObject(contentAsString);

                        // New User
                        if (requestName.equals("NewUser")) {

                            String tempToken = jsonObject.getString("token");
                            String tempUserID = jsonObject.getString("user_id");

                            if (tempToken != null && tempToken.length() > 0) {

                                userToken = "Token " +tempToken;
                                Log.i(LOGTAG, "saving the token " +userToken);
                                SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.app_preferences), Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPref.edit();
                                editor.putString("UserToken", userToken);
                                editor.putString("UserID", tempUserID);
                                editor.commit();

                                // Request content
                                indexArticlesForCategories();
                            }
                        }
                        // Index articles
                        else if (requestName.equals("IndexArticlesForCategories")) {

                            Log.i(LOGTAG,"got here");
                        }
                        // User Profile
                        else if (requestName.equals("UserProfile")) {

                            Log.i(LOGTAG, "the user id is " +jsonObject.getString("user_id"));
                        }

                    }
                    catch (JSONException e) {
                        Log.i(LOGTAG, "json exception " +e.getMessage());
                        e.printStackTrace();
                        Log.getStackTraceString(e.getCause().getCause());
                    }

                    Log.i(LOGTAG, "the json data " + contentAsString);
                }



                return contentAsString;

                // Makes sure that the InputStream is closed after the app is finished using it.
            } finally {
                if (is != null) {

                    is.close();
                }
            }
        }

        // convert input stream to text
        public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
//            Reader reader = null;
//            reader = new InputStreamReader(stream, "UTF-8");
//            char[] buffer = new char[len];
//            reader.read(buffer);
//            return new String(buffer);

            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));

            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }



            return sb.toString();
        }

堆栈跟踪(更新):

java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
        at java.util.concurrent.FutureTask.run(FutureTask.java:239)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
        Caused by: java.lang.NullPointerException
        at com.media24.myedit.WebServicesManager$AsyncDownloadTask.downloadUrl(WebServicesManager.java:248)
        at com.media24.myedit.WebServicesManager$AsyncDownloadTask.doInBackground(WebServicesManager.java:140)
        at com.media24.myedit.WebServicesManager$AsyncDownloadTask.doInBackground(WebServicesManager.java:126)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        ... 4 more

最佳答案

我没有检查你的代码,但我总是使用下面的代码 fragment ,它一直有效。

JSONParser.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

然后这样调用它:

JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);

有时 json 以数组节点而不是 jSON 对象节点开头。在这种情况下,您必须返回 JSONArray 而不是 JSONObject

关于android - JSONObject 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17809816/

相关文章:

json - 在 mac 上显示我的工具栏 (Node-Webkit)

python - 如何将网页中的 JSON 转换为 Python 脚本

PHP 数组转 JSON

java - 从内部类中返回类型 void 的重写方法返回

java - 如何从Gson获取变量的值

java - Json Gson 绑定(bind)不起作用(异常对象/字符串)

asp.net-mvc - 更改 ASP MVC3 中使用的默认 JSON 序列化程序

android - 在 Android Studio 中更改字体样式有哪些不同方法

android - 如何在 Flutter dart 上使用 dwolla api

python - 如何在 Python 中从 JSON 对象中提取数据?