如何解析这个简单的JSON数据

时间:2014-02-21 05:04:31

标签: java android json parsing

我一直在学习解析Android中的json数据。我能够解析我所遵循的示例中的json数据。为了测试我自己,我开始解析一些新的json数据。我在下面看到了这个json数据:

    {"errors":[{"message":"Bad Authentication data","code":215}]}

我无法解析它:(

下面是我解析json的代码:

    public JSONObject getJSONFromURL(String url){
    JSONObject receivedJSON = null;

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    try {
        HttpResponse response = client.execute(request);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if(statusCode != 200){
            return null;
        }
        //Getting stream of data returned from the server using InputStream
        InputStream streamReceived = response.getEntity().getContent();
        //Reading stream of data using BufferedReader
        BufferedReader reader = new BufferedReader(new InputStreamReader(streamReceived));
        StringBuilder builder = new StringBuilder();
        String line = null;
        //Reading each line of the received data
        while((line = reader.readLine()) != null){
            builder.append(line);
        }
        streamReceived.close();
        //Converting the data read into String using StringBuilder
        String jsonData = builder.toString();
        //Converting String into JSONObject
        receivedJSONData = new JSONObject(jsonData);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //returning the JSONObject
    return receivedJSON;
}

在我的MainActivity中,我获取了JSONObject并相应地从中获取信息。我是这样做的:

    JSONObject jsonObj = jsonParser.getJSONFromURL(twitterURL);
    JSONArray erros = jsonObj.getJSONArray("errors");
    JSONObject error = erros.getJSONObject(0);
    String msg = error.getString("message");
    Log.d("Twitter Data", msg);

如果将上述json字符串中的“错误”视为对象或数组,我感到很困惑。

以下是我的logcat错误:

02-21 10:21:08.391: E/AndroidRuntime(972): FATAL EXCEPTION: AsyncTask #1
    02-21 10:21:08.391: E/AndroidRuntime(972): java.lang.RuntimeException: An                error      occured while executing doInBackground()
    02-21 10:21:08.391: E/AndroidRuntime(972):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at java.lang.Thread.run(Thread.java:856)
    02-21 10:21:08.391: E/AndroidRuntime(972): Caused by: java.lang.NullPointerException
    02-21 10:21:08.391: E/AndroidRuntime(972):  at com.example.youtubevideolist.MainActivity$FetchYoutubeVideos.doInBackground(MainActivity.java:77)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at com.example.youtubevideolist.MainActivity$FetchYoutubeVideos.doInBackground(MainActivity.java:1)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
    02-21 10:21:08.391: E/AndroidRuntime(972):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
    02-21 10:21:08.391: E/AndroidRuntime(972):  ... 4 more
    02-21 10:21:09.731: E/WindowManager(972): Activity com.example.youtubevideolist.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40ce51d8 V.E..... R......D 0,0-729,324} that was originally added here
    02-21 10:21:09.731: E/WindowManager(972): android.view.WindowLeaked: Activity com.example.youtubevideolist.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40ce51d8 V.E..... R......D 0,0-729,324} that was originally added here
    02-21 10:21:09.731: E/WindowManager(972):   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
    02-21 10:21:09.731: E/WindowManager(972):   at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
    02-21 10:21:09.731: E/WindowManager(972):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
    02-21 10:21:09.731: E/WindowManager(972):   at android.app.Dialog.show(Dialog.java:281)
    02-21 10:21:09.731: E/WindowManager(972):   at com.example.youtubevideolist.MainActivity$FetchYoutubeVideos.onPreExecute(MainActivity.java:56)
    02-21 10:21:09.731: E/WindowManager(972):   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
    02-21 10:21:09.731: E/WindowManager(972):   at android.os.AsyncTask.execute(AsyncTask.java:534)
    02-21 10:21:09.731: E/WindowManager(972):   at com.example.youtubevideolist.MainActivity.onCreate(MainActivity.java:38)
    02-21 10:21:09.731: E/WindowManager(972):   at android.app.Activity.performCreate(Activity.java:5104)
    02-21 10:21:09.731: E/WindowManager(972):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    02-21 10:21:09.731: E/WindowManager(972):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    02-21 10:21:09.731: E/WindowManager(972):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    02-21 10:21:09.731: E/WindowManager(972):   at android.app.ActivityThread.access$600(ActivityThread.java:141)
    02-21 10:21:09.731: E/WindowManager(972):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    02-21 10:21:09.731: E/WindowManager(972):   at android.os.Handler.dispatchMessage(Handler.java:99)
    02-21 10:21:09.731: E/WindowManager(972):   at android.os.Looper.loop(Looper.java:137)
    02-21 10:21:09.731: E/WindowManager(972):   at android.app.ActivityThread.main(ActivityThread.java:5041)
    02-21 10:21:09.731: E/WindowManager(972):   at java.lang.reflect.Method.invokeNative(Native Method)
    02-21 10:21:09.731: E/WindowManager(972):   at java.lang.reflect.Method.invoke(Method.java:511)
    02-21 10:21:09.731: E/WindowManager(972):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    02-21 10:21:09.731: E/WindowManager(972):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    02-21 10:21:09.731: E/WindowManager(972):   at dalvik.system.NativeStart.main(Native   Method)

非常感谢任何帮助:)在此先感谢:)

2 个答案:

答案 0 :(得分:1)

信息部分是:

Caused by: java.lang.NullPointerException
at com.example.youtubevideolist.MainActivity$FetchYoutubeVideos.doInBackground(MainActivity.java:77)

所以你在那一行上有一个NullPointerException。

如果您还没有看到问题,欢迎您在发布的代码中标记该行,此处的人员会告诉您可能出现的问题。

答案 1 :(得分:1)

这看起来像是从您拥有的方法返回的字符串的问题!就我的直觉而言,返回一个空字符串。

我尝试按照代码运行

String jsonString = "{\"errors\":[{\"message\":\"Bad Authentication data\",\"code\":215}]}";
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray erros = jsonObj.getJSONArray("errors");
JSONObject error;
error = erros.getJSONObject(0);
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();

在尝试解析JSON之前检查字符串的内容

编辑:

作为一个好的做法总是进行空检查,特别是因为你明确地有一行可以返回一个空字符串!