使用 JsonReader 类 Android 解析 Json

Posted

技术标签:

【中文标题】使用 JsonReader 类 Android 解析 Json【英文标题】:Parsing Json using JsonReader Class Android 【发布时间】:2012-12-05 17:28:02 【问题描述】:

我是一名新的 android 开发人员,无法使用 JsonReader 类解析 JSON InputStream。每当它到达 reader.beginArray() 开始解析 InputStream 时,它就会崩溃。我以http://developer.android.com/reference/android/util/JsonReader.html 的代码为例。有人可以帮我解决这个问题吗?顺便说一句,我正在使用 JsonReader 类,因为我在其他调用中消耗了大量文本。

我正在传递以下网址:--- 已删除 ---

public class JSONParser 

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    static JsonReader reader = null;
    // constructor
    public JSONParser() 

    



    public List getJSONFromUrl(String url) throws IOException 

        // Making HTTP request

            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

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



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







            try 
                reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
             catch (UnsupportedEncodingException e1) 
                // TODO Auto-generated catch block
                e1.printStackTrace();
            

            List<Message> messages = new ArrayList<Message>();
            try 
            reader.beginArray();
            while (reader.hasNext()) 
              messages.add(readMessage(reader));
            
            reader.endArray();
            
            catch (IOException e)
            
                e.printStackTrace();
            

                return messages;




        // try parse the string to a JSON object


        // return JSON String
        //return reader;

    



    public Message readMessage(JsonReader reader) throws IOException 
        long _id = -1;
        String topic_title = null;
        Integer sort_order = null;

        reader.beginObject();
         while (reader.hasNext()) 
           String name = reader.nextName();
           if (name.equals("id")) 
               _id = reader.nextLong();
            else if (name.equals("topic_title")) 
               topic_title = reader.nextString();

                      
           else if (name.equals("sort_order")) 
               sort_order = reader.nextInt();

           
           else 
               reader.skipValue();
           
         
         reader.endObject();
         DataBaseHelper.getInstance().updateTopicOrder(_id, sort_order, topic_title);
        return new Message();
      



这是我的日志:

12-05 10:08:54.806: D/gralloc_goldfish(582): Emulator without GPU emulation detected.
12-05 10:08:56.367: D/dalvikvm(582): GC_CONCURRENT freed 146K, 3% free 10139K/10375K, paused 19ms+10ms
12-05 10:12:17.466: W/webcore(582): java.lang.Throwable: EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up.
12-05 10:12:17.466: W/webcore(582):     at android.webkit.WebViewCore$EventHub.removeMessages(WebViewCore.java:1671)
12-05 10:12:17.466: W/webcore(582):     at android.webkit.WebViewCore$EventHub.access$7800(WebViewCore.java:920)
12-05 10:12:17.466: W/webcore(582):     at android.webkit.WebViewCore.removeMessages(WebViewCore.java:1783)
12-05 10:12:17.466: W/webcore(582):     at android.webkit.WebView.sendOurVisibleRect(WebView.java:2858)
12-05 10:12:17.466: W/webcore(582):     at android.webkit.ZoomManager.setZoomScale(ZoomManager.java:586)
12-05 10:12:17.466: W/webcore(582):     at android.webkit.ZoomManager.access$1700(ZoomManager.java:49)
12-05 10:12:17.466: W/webcore(582):     at android.webkit.ZoomManager$PostScale.run(ZoomManager.java:977)
12-05 10:12:17.466: W/webcore(582):     at android.os.Handler.handleCallback(Handler.java:605)
12-05 10:12:17.466: W/webcore(582):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-05 10:12:17.466: W/webcore(582):     at android.os.Looper.loop(Looper.java:137)
12-05 10:12:17.466: W/webcore(582):     at android.app.ActivityThread.main(ActivityThread.java:4340)
12-05 10:12:17.466: W/webcore(582):     at java.lang.reflect.Method.invokeNative(Native Method)
12-05 10:12:17.466: W/webcore(582):     at java.lang.reflect.Method.invoke(Method.java:511)
12-05 10:12:17.466: W/webcore(582):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-05 10:12:17.466: W/webcore(582):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-05 10:12:17.466: W/webcore(582):     at dalvik.system.NativeStart.main(Native Method)
12-05 10:12:19.146: D/dalvikvm(582): GC_CONCURRENT freed 179K, 4% free 10370K/10695K, paused 5ms+8ms
12-05 10:12:19.616: W/dalvikvm(582): threadid=13: thread exiting with uncaught exception (group=0x409961f8)
12-05 10:12:19.672: E/AndroidRuntime(582): FATAL EXCEPTION: AsyncTask #2
12-05 10:12:19.672: E/AndroidRuntime(582): java.lang.RuntimeException: An error occured while executing doInBackground()
12-05 10:12:19.672: E/AndroidRuntime(582):  at android.os.AsyncTask$3.done(AsyncTask.java:278)
12-05 10:12:19.672: E/AndroidRuntime(582):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-05 10:12:19.672: E/AndroidRuntime(582):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-05 10:12:19.672: E/AndroidRuntime(582):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-05 10:12:19.672: E/AndroidRuntime(582):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-05 10:12:19.672: E/AndroidRuntime(582):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
12-05 10:12:19.672: E/AndroidRuntime(582):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-05 10:12:19.672: E/AndroidRuntime(582):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-05 10:12:19.672: E/AndroidRuntime(582):  at java.lang.Thread.run(Thread.java:856)
12-05 10:12:19.672: E/AndroidRuntime(582): Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
12-05 10:12:19.672: E/AndroidRuntime(582):  at android.util.JsonReader.expect(JsonReader.java:310)
12-05 10:12:19.672: E/AndroidRuntime(582):  at android.util.JsonReader.beginArray(JsonReader.java:277)
12-05 10:12:19.672: E/AndroidRuntime(582):  at com.gotquestions.gqandapp.util.JSONParser.readMessagesArray(JSONParser.java:82)
12-05 10:12:19.672: E/AndroidRuntime(582):  at com.gotquestions.gqandapp.util.JSONParser.getJSONFromUrl(JSONParser.java:73)
12-05 10:12:19.672: E/AndroidRuntime(582):  at com.gotquestions.gqandapp.ac.UpdaterActivity$updateTopics.doInBackground(UpdaterActivity.java:108)
12-05 10:12:19.672: E/AndroidRuntime(582):  at com.gotquestions.gqandapp.ac.UpdaterActivity$updateTopics.doInBackground(UpdaterActivity.java:1)
12-05 10:12:19.672: E/AndroidRuntime(582):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-05 10:12:19.672: E/AndroidRuntime(582):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-05 10:12:19.672: E/AndroidRuntime(582):  ... 5 more
12-05 10:12:24.938: I/Process(582): Sending signal. PID: 582 SIG: 9
12-05 10:14:39.988: W/ActivityThread(645): Application com.gotquestions.gqandapp is waiting for the debugger on port 8100...
12-05 10:14:40.097: I/System.out(645): Sending WAIT chunk
12-05 10:14:40.137: I/dalvikvm(645): Debugger is active
12-05 10:14:40.216: I/System.out(645): Debugger has connected
12-05 10:14:40.216: I/System.out(645): waiting for debugger to settle...
12-05 10:14:40.416: I/System.out(645): waiting for debugger to settle...
12-05 10:14:40.617: I/System.out(645): waiting for debugger to settle...
12-05 10:14:40.817: I/System.out(645): waiting for debugger to settle...
12-05 10:14:41.027: I/System.out(645): waiting for debugger to settle...
12-05 10:14:41.228: I/System.out(645): waiting for debugger to settle...
12-05 10:14:41.427: I/System.out(645): waiting for debugger to settle...
12-05 10:14:41.627: I/System.out(645): waiting for debugger to settle...
12-05 10:14:41.827: I/System.out(645): waiting for debugger to settle...
12-05 10:14:42.052: I/System.out(645): waiting for debugger to settle...
12-05 10:14:42.247: I/System.out(645): waiting for debugger to settle...
12-05 10:14:42.462: I/System.out(645): waiting for debugger to settle...
12-05 10:14:42.674: I/System.out(645): waiting for debugger to settle...
12-05 10:14:42.881: I/System.out(645): waiting for debugger to settle...
12-05 10:14:43.086: I/System.out(645): debugger has settled (1352)
12-05 10:14:46.566: D/gralloc_goldfish(645): Emulator without GPU emulation detected.
12-05 10:14:47.616: D/dalvikvm(645): GC_CONCURRENT freed 149K, 3% free 10138K/10375K, paused 6ms+6ms
12-05 10:19:45.851: D/dalvikvm(645): Debugger has detached; object registry had 594 entries
12-05 10:21:11.577: W/ActivityThread(707): Application com.gotquestions.gqandapp is waiting for the debugger on port 8100...
12-05 10:21:11.668: I/System.out(707): Sending WAIT chunk
12-05 10:21:11.677: I/dalvikvm(707): Debugger is active
12-05 10:21:11.747: I/System.out(707): Debugger has connected
12-05 10:21:11.747: I/System.out(707): waiting for debugger to settle...
12-05 10:21:11.987: I/System.out(707): waiting for debugger to settle...
12-05 10:21:12.197: I/System.out(707): waiting for debugger to settle...
12-05 10:21:12.397: I/System.out(707): waiting for debugger to settle...
12-05 10:21:12.597: I/System.out(707): waiting for debugger to settle...
12-05 10:21:12.799: I/System.out(707): waiting for debugger to settle...
12-05 10:21:13.007: I/System.out(707): waiting for debugger to settle...
12-05 10:21:13.207: I/System.out(707): waiting for debugger to settle...
12-05 10:21:13.407: I/System.out(707): waiting for debugger to settle...
12-05 10:21:13.607: I/System.out(707): waiting for debugger to settle...
12-05 10:21:13.820: I/System.out(707): waiting for debugger to settle...
12-05 10:21:14.017: I/System.out(707): waiting for debugger to settle...
12-05 10:21:14.227: I/System.out(707): waiting for debugger to settle...
12-05 10:21:14.427: I/System.out(707): waiting for debugger to settle...
12-05 10:21:14.626: I/System.out(707): waiting for debugger to settle...
12-05 10:21:14.864: I/System.out(707): waiting for debugger to settle...
12-05 10:21:15.078: I/System.out(707): debugger has settled (1364)
12-05 10:21:18.457: D/gralloc_goldfish(707): Emulator without GPU emulation detected.
12-05 10:21:19.567: D/dalvikvm(707): GC_CONCURRENT freed 151K, 3% free 10136K/10375K, paused 7ms+7ms
12-05 10:21:28.467: D/dalvikvm(707): GC_CONCURRENT freed 160K, 3% free 10401K/10695K, paused 6ms+8ms

【问题讨论】:

您使用的是哪个安卓操作系统?当应用崩溃时不要忘记发布Logcat 我使用的是 Android 4.0。我会附上logcat...谢谢 hmm,那么我猜问题出在reader.beginArray(); 它接缝你正在阅读JsonObject 作为JsonArray 让我们continue this discussion in chat ...预期 BEGIN_ARRAY 但是 BEGIN_OBJECT ...这意味着您的 json 从对象而不是数组开始...它的对象具有名为 ropics 的属性,并且该属性是数组...所以首先您应该使用这个起始对象和名称 【参考方案1】:

你的日志说

12-05 10:12:19.672: E/AndroidRuntime(582): Caused by: java.lang.IllegalStateException: 应为 BEGIN_ARRAY 但为 BEGIN_OBJECT

在 Json 格式中,“”是对象,“[]”是数组

查看您的 json 文件,我认为它以对象开头。如果从对象开始,请更改您的代码行以读取对象而不是数组开始。

try 
        reader.beginObject();
        while (reader.hasNext()) 
          messages.add(readMessage(reader));
        
        reader.endObject();
        

注意:使用后关闭流。常见的做法是将代码放入 finally 块中。

【讨论】:

以上是关于使用 JsonReader 类 Android 解析 Json的主要内容,如果未能解决你的问题,请参考以下文章

[转]Java Code Examples for android.util.JsonReader

使用 JsonReader

如何修复 Android Studio 中的“使用 JsonReader.setLenient(true) 在第 1 行第 1 列路径 $ 处接受格式错误的 JSON”错误

在 android 的 API 8 中使用 JSON Reader

spray-json 找不到 List[T] 类型的 JsonReader

Gson全解析之一:JsonReader的beginObject()