简体   繁体   English

Android:JSON解析错误

[英]Android: JSON parsing error

I am getting error in my app. 我的应用程序出现错误。 I am doing the JSON parsing. 我正在执行JSON解析。 The parsing is ok, but where is the issue occurs i am not getting. 解析还可以,但是问题出在哪里,我没有得到。

My JSON is: 我的JSON是:

{"status":1,
        "magazines":[{
            "magazinetitle": "Test Magazine 1",
            "magazineid": 100,
            "magazinecoverthumburl": "pages/page1.jpg",
            "magazinecoverlargeurl": "pages/page1.jpg",
            "pages":[{
                "pagenumber": 1,
                "thumburl":"pages/page1.jpg",
                "largeurl":"pages/page1.jpg",
                "subpages": [{
                                "pagenumber": 1,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 2,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 3,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 4,
                                "pagetype": "image"
                            }]
            },
            {
                "pagenumber": 2,
                "thumburl":"pages/page2.jpg",
                "largeurl":"pages/page2.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 3,
                "thumburl":"pages/page3.jpg",
                "largeurl":"pages/page3.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 4,
                "thumburl":"pages/page4.jpg",
                "largeurl":"pages/page4.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 5,
                "thumburl":"pages/page5.jpg",
                "largeurl":"pages/page5.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 6,
                "thumburl":"pages/page6.jpg",
                "largeurl":"pages/page6.jpg",
                "subpages": [{
                                "pagenumber": 1,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 2,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 3,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 4,
                                "pagetype": "image"
                            }]
            },
            {
                "pagenumber": 7,
                "thumburl":"pages/page7.jpg",
                "largeurl":"pages/page7.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 8,
                "thumburl":"pages/page8.jpg",
                "largeurl":"pages/page8.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 9,
                "thumburl":"pages/page15.jpg",
                "largeurl":"pages/page15.jpg",
                "subpages": [{
                                "pagenumber": 1,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 2,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 3,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 4,
                                "pagetype": "image"
                            }]
            },              
            {
                "pagenumber": 10,
                "thumburl":"pages/page8.jpg",
                "largeurl":"pages/page8.jpg",
                "subpages":[]
            }]
        },
        {
            "magazinetitle": "Test Magazine 2",
            "magazineid": 101,
            "magazinecoverthumburl": "pages/page2.jpg",
            "magazinecoverlargeurl": "pages/page2.jpg",
            "pages":[{
                "pagenumber": 1,
                "thumburl":"pages/page1.jpg",
                "largeurl":"pages/page1.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 2,
                "thumburl":"pages/page2.jpg",
                "largeurl":"pages/page2.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 3,
                "thumburl":"pages/page3.jpg",
                "largeurl":"pages/page3.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 4,
                "thumburl":"pages/page4.jpg",
                "largeurl":"pages/page4.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 5,
                "thumburl":"pages/page5.jpg",
                "largeurl":"pages/page5.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 6,
                "thumburl":"pages/page6.jpg",
                "largeurl":"pages/page6.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 7,
                "thumburl":"pages/page7.jpg",
                "largeurl":"pages/page7.jpg",
                "subpages": [{
                                "pagenumber": 1,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 2,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 3,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 4,
                                "pagetype": "image"
                            }]
            },
            {
                "pagenumber": 8,
                "thumburl":"pages/page13.jpg",
                "largeurl":"pages/page13.jpg",
                "subpages":[]
            },
            {
                "pagenumber": 9,
                "thumburl":"pages/page14.jpg",
                "largeurl":"pages/page14.jpg",
                "subpages": [{
                                "pagenumber": 1,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 2,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 3,
                                "pagetype": "video"
                            },
                            {
                                "pagenumber": 4,
                                "pagetype": "image"
                            }]
            }]
        // And so on magazine, pages, subpages are there...
        }]}

My code is of do in background is as follows: 我的代码是在后台执行的,如下所示:

Global Variable is 全局变量为

// contacts JSONArray
public static JSONArray status = null, magazines = null, pages = null, subpages = null;

doInBackground(Void... arg0) code: doInBackground(Void ... arg0)代码:

// Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                status = jsonObj.getJSONArray(TAG_MAGAZINES);

                Magazine magazine1 = new Magazine();                    

                // looping through All Contacts
                for (int i = 0; i < status.length(); i++) {
                    JSONObject magazine = status.getJSONObject(i);                      

                    String magazineTitle = magazine.getString(TAG_MAGAZINETITLE);
                    magazine1.setMagazineTitle(magazineTitle);
                    magazine1.setMagazineid(String.valueOf(magazine.getInt(TAG_MAGAZINEID)));
                    magazine1.setMagazinecoverthumburl(magazine.getString(TAG_MAGAZINECOVERTHUMBURL));
                    magazine1.setMagazinecoverlargeurl(magazine.getString(TAG_MAGAZINECOVERLARGEURL));

                    String magazineCoverThumbURL = magazine.getString(TAG_MAGAZINECOVERTHUMBURL);
                    String magazineCoverLargeURL = magazine.getString(TAG_MAGAZINECOVERLARGEURL);*/

                    JSONObject jsonObjInnerString = status.getJSONObject(i);
                    pages = jsonObjInnerString.getJSONArray(TAG_PAGES);
                    Pages pagesModel = new Pages();

                    // looping through All Contacts
                    for (int j = 0; j < pages.length(); j++) {
                        JSONObject pagesObject = pages.getJSONObject(j);

                        pagesModel.setPagenumber(String.valueOf(pagesObject.getInt(TAG_PAGENUMBER)));
                        pagesModel.setThumburl(pagesObject.getString(TAG_THUMBURL));
                        pagesModel.setLargeurl(pagesObject.getString(TAG_LARGEURL));
                        magazine1.setPages(pagesModel);

                        JSONObject jsonObjSubInnerString = pages.getJSONObject(j);
                        subpages = jsonObjSubInnerString.getJSONArray(TAG_SUBPAGES);

                        SubPages subPagesModel = new SubPages();

                        // looping through All Contacts
                        for (int k = 0; k < subpages.length(); k++) {
                            Log.d("k",String.valueOf(k));

                            JSONObject subPagesObject = subpages.getJSONObject(k);

                            subPagesModel.setSubpagenumber(String.valueOf(subPagesObject.getInt(TAG_SUBPAGENUMBER)));
                            Log.d("SPgno",String.valueOf(subPagesObject.getInt(TAG_SUBPAGENUMBER)));
                            subPagesModel.setSubpagetype(subPagesObject.getString(TAG_SUBPAGETYPE));
                            subPagesModel.setSubpageurl(subPagesObject.getString(TAG_SUBPAGEURL));
                            pagesModel.setSubPages(subPagesModel);
                        }
                    }

                    // tmp hashmap for single contact
                    HashMap<String, String> magazineDetailsHashMap = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    magazineDetailsHashMap.put(TAG_MAGAZINETITLE, magazineTitle);
                    //magazineDetailsHashMap.put(TAG_MAGAZINEID, magazineID);

                    // adding contact to contact list
                    magazineDetails.add(magazine1);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;

And the code of magzine class is as follows: 而杂志类的代码如下:

int count = MainActivity.status.length(),l=0;
public String[] magazineTitle = new String[count], magazineid = new String[count], magazinecoverthumburl = new String[count], magazinecoverlargeurl = new String[count];
public Pages[] pages = new Pages[count];
public String[] getMagazineTitle() {
    return magazineTitle;
}
public void setMagazineTitle(String magazineTitle) {
    this.magazineTitle[l] = magazineTitle;
}
public String[] getMagazineid() {
    return magazineid;
}
public void setMagazineid(String magazineid) {
    this.magazineid[l] = magazineid;
}
public String[] getMagazinecoverthumburl() {
    return magazinecoverthumburl;
}
public void setMagazinecoverthumburl(String magazinecoverthumburl) {
    this.magazinecoverthumburl[l] = magazinecoverthumburl;
}
public String[] getMagazinecoverlargeurl() {
    return magazinecoverlargeurl;
}
public void setMagazinecoverlargeurl(String magazinecoverlargeurl) {
    this.magazinecoverlargeurl[l] = magazinecoverlargeurl;
}
public Pages[] getPages() {
    return pages;
}
public void setPages(Pages pages) {
    this.pages[l] = pages;
    l++;
}

Error is as follows: 错误如下:

2-27 12:01:12.255: W/dalvikvm(15169): threadid=10: thread exiting with uncaught exception (group=0x4001e578)
02-27 12:01:12.255: E/AndroidRuntime(15169): FATAL EXCEPTION: AsyncTask #1
02-27 12:01:12.255: E/AndroidRuntime(15169): java.lang.RuntimeException: An error occured while executing doInBackground()
02-27 12:01:12.255: E/AndroidRuntime(15169):    at android.os.AsyncTask$3.done(AsyncTask.java:200)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at java.lang.Thread.run(Thread.java:1019)
02-27 12:01:12.255: E/AndroidRuntime(15169): Caused by: java.lang.ArrayIndexOutOfBoundsException
02-27 12:01:12.255: E/AndroidRuntime(15169):    at com.oi.jsonparsingnestingdemo.model.Magazine.setPages(Magazine.java:37)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at com.oi.jsonparsingnestingdemo.MainActivity$GetMagazineDetails.doInBackground(MainActivity.java:137)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at com.oi.jsonparsingnestingdemo.MainActivity$GetMagazineDetails.doInBackground(MainActivity.java:1)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
02-27 12:01:12.255: E/AndroidRuntime(15169):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
02-27 12:01:12.255: E/AndroidRuntime(15169):    ... 4 more

Caused by: java.lang.ArrayIndexOutOfBoundsException 02-27 12:01:12.255: E/AndroidRuntime(15169): at com.oi.jsonparsingnestingdemo.model.Magazine.setPages(Magazine.java:37) 引起原因:java.lang.ArrayIndexOutOfBoundsException 02-27 12:01:12.255:E / AndroidRuntime(15169):at com.oi.jsonparsingnestingdemo.model.Magazine.setPages(Magazine.java:37)

It seems that when setting your pages the inner array pages might not be initialized correctly. 似乎在设置页面时,内部数组pages可能未正确初始化。 Please check if int count = MainActivity.status.length(); 请检查int count = MainActivity.status.length(); returns the value you are expecting 返回您期望的值

Even though the first answer might help you I would definitely advise you towards using json parsing libraries. 即使第一个答案可能对您有帮助,我也绝对会建议您使用json解析库。 In this particluar case I use GSON . 在这种特殊情况下,我使用GSON

in Magazine.java: 在Magazine.java中:

public class Magazine {
 private String magazinetitle;
 private int magazineid;
 private String magazinecoverthumburl;
 private String magazinecoverlargeurl;
 private List<Page> pages;
 // declare getters for the same fields if you need to read them
 // Setters are not a requirement
}

in Response.java 在Response.java中

public class Response{
 private int status;
 private List<Magazine> magazines;
 // declare getters for the same fields if you need to read them
 // Setters are not a requirement
}

Actually you can happily live without this class and combine JSONObject and GSON parsing, but now JSONObject approach seems so cumbersome to me. 实际上,您可以不用该类而愉快地生活,并结合使用JSONObject和GSON解析,但是现在JSONObject方法对我而言似乎很麻烦。

Now your doInBackground turns to be: 现在,您的doInBackground变为:

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);
Gson gson = new Gson();
Response response = gson.parse(jsonStr , Response.class);

This will fill in all the fields you need. 这将填写您需要的所有字段。 I am not kidding. 我是认真的。 You do not need to make any manual parsing yourself. 您不需要自己进行任何手动解析。 You will not have any way to cause an error. 您将不会有任何方式导致错误。

For more advanced usage you can also use the @SerializedName annotation to make the java fields be beautifully camelCased rather than confusinggly several words in the same case. 对于更高级的用法,您还可以使用@SerializedName批注使Java字段具有精美的驼峰式@SerializedName ,而不会在相同情况下混淆多个单词。

Best solution would be as Boris Strandjev pointed out, to use GSON. 正如Boris Strandjev所指出的,最佳解决方案是使用GSON。 If you want to avoid using the library and continue doing the parsing yourself you could: 如果要避免使用该库并继续自己进行解析,则可以:

setPages(Pages pages)
{
if(pages.length >= l-1)
return;
this.pages[l] = pages;
    l++;
}

This should prevent you app from crashing. 这样可以防止您的应用崩溃。 You should pass the page count in the Magazine constructor and not access it statically. 您应该在Magazine构造函数中传递页数,而不要静态访问它。

@MarioStoilov answer is the correct one. @MarioStoilov的答案是正确的。 He is pointing you in the right direction. 他为您指明了正确的方向。 You are crashing because of an ArrayIndexOutOfBoundsException due to: 您由于ArrayIndexOutOfBoundsException而崩溃,原因是:

int count = MainActivity.status.length();//is the issue

Your crash is happening because of: 您的当机发生是因为:

public void setPages(Pages pages) { //by the way. here, I would change "Pages pages" to "Pages  page" because your getting one page from the many pages
    this.pages[l] = pages;
    l++;
}

Why?.... 为什么?....

Well lets say you do this: 好吧,说你这样做:

int count =0;
public Pages[] pages = new Pages[count];

Then you try to do this: 然后,您尝试执行以下操作:

Pages onePage = pages[0];

You will get an ArrayIndexOutOfBoundsException. 您将获得ArrayIndexOutOfBoundsException。 To ask for and item out of "pages[]" it will at lest need to have one item in it. 要从“ pages []”中请求项,则至少需要其中一项。 It does not matter if the item is empty. 该项是否为空无关紧要。 it still needs to have one. 它仍然需要一个。 The only way your code will work is if count is = or > 1. NEVER 0 您的代码将起作用的唯一方法是,如果count是=或>1。从不0

 int count =1;//this MUST be greater then 0 never never 0 or will crash 
public Pages[] pages = new Pages[count];

public void setPages(Pages pages) {
    this.pages[l] = pages;
    l++;
}

But this all points to a bigger issue with your code. 但这一切都指向您的代码更大的问题。 Let's say you get your code running 100%. 假设您的代码可以100%运行。 Well now you're relying on the JSON to always always always return a value greater than 0. And I'm not sure the purpose of your code but maybe that will be the case. 好了,现在您依靠JSON始终总是返回一个大于0的值。我不确定您的代码的目的,但事实可能如此。 And in your production version of your code you will always get a value greater than 0. Maybe so, but in that rare case, if you ever get a 0 from the JSON it will crash. 并且在代码的生产版本中,您将始终获得大于0的值。也许是这样,但是在极少数情况下,如果从JSON获得0,它将崩溃。 No matter what. 无论。 Again I'm not sure what will cause you to get a 0 from the JSON in real world scenario but if you ever ever get a 0 it will crash. 同样,我不确定在现实情况下是什么导致您从JSON中获得0,但是如果您获得0,它将崩溃。 My recommendations would be to wrap the set pages: void in a try and catch 我的建议是包装设置的页面:尝试捕获无效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM