JSON解析从URL出现异常:错误分析数据org.json.JSONException:未终结阵列人品115阵列、人品、异常、错误

2023-09-05 04:49:09 作者:满天ぐ星光垂

我解析此网址,我已经有一个例外,不知道如何跳过它结束了......我需要得到100个最流行的应用程序只有名字。还有关键的IM:name和它内部的关键勒贝尔,但我认为它是无效的JsonArray,所以我需要找到办法通过密钥来获得名字IM:名字......有SMB任何想法我怎么能解决这个问题?

I'm parsing this url and I've got an exception and don't know how to skip it over... I need to get only names of 100 the most popular apps. There is key "im:name" and inside of it key "lebel", but as I see it is invalid JsonArray, so I need to find the way to get names by the key "im:name"... has smb any ideas how can I fix this?

这是我的 AsyncTask.class

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

    String jsonStringUrl = "https://itunes.apple.com/br/rss/topfreeapplications/limit=100/json";
    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(jsonStringUrl);
            // get the array of users
//HERE I NEED TO CHANGE SOMETHING
            dataJsonArr = json.getJSONArray("feed"); // probably wrong
            // loop through all users
            for (int i = 0; i < dataJsonArr.length(); i++) {
                JSONObject c = dataJsonArr.getJSONObject(i);
                // Storing each json item in variable
                String name = c.getString("im:name");//probably wrong
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

和这是日志

    09-10 20:04:03.013  18211-18241/com.yuretsrodik.top100apps E/JsonParser.java﹕ Error parsing data org.json.JSONException: Unterminated array at character 115 of {"feed":{"author":{"name":{"label":"iTunes Store"}, "uri":{"label":"http://www.apple.com/br/itunes/"}}, "entry":[n{"im:name":{"label":"Messenger"}, "im:image":[n{"label":"http://a474.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.53x53-50.png", "attributes":{"height":"53"}}, n{"label":"http://a990.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.75x75-65.png", "attributes":{"height":"75"}}, n{"label":"http://a1675.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.100x100-75.png", "attributes":{"height":"100"}}], "summary":{"label":"lcance instantaneamente as pessoas na sua vida, gratuitamente. O Messenger é como mensagens de texto, mas você não precisa pagar por cada mensagem (funciona com o seu plano de dados). \n\nNão é só para amigos no Facebook: envie mensagens para as pessoas na sua agenda de contatos e basta inserir um número de telefone para adicionar um novo contato.\n\nBate-papos em grupo: crie grupos para as pessoas a quem você mais envia mensagens. Dê um nome a eles, defina fotos para o grupo e os mantenha em um só lugar.\n\nFotos e vídeos: grave vídeos e tire selfies ou outras fotos diretamente do aplicativo e envie-os com um toque.\n\nLigações gratuitas: fale por quanto tempo quiser, mesmo com pessoas em outros países. (Ligações são gratuitas somente através do Wi-Fi. Do contrário, cobranças de dados padrão são aplicáveis).\n\nMais formas de enviar mensagens: \nDê vida às suas conversas com as figurinhas. \nVeja uma prévia das suas fotos e vídeos no rolo da câmera sem sair da conversa, e escolha as melhores para enviar.\nGrave mensagens de voz quando tiver mais para dizer\n\nRecursos adicionais:\nSaiba quando as pessoas viram suas mensagens.\nEncaminhe mensagens ou fotos para as pessoas que não estavam na conversa.\nProcure pessoas e grupos para entrar em contato com eles rapidamente.\nAtive a localização para que as pessoas saibam que você está nas imediações.\nVeja quem está disponível no Messenger e quem está on-line no Facebook. \nDesative as notificações quando você estiver trabalhando, dormindo ou se precisar dar um tempo.\nFique conectado para nunca perder uma mensagem."}, "im:price":{"label":"Grátis", "attributes":{"amount":"0.00000", "currency":"USD"}}, "im:contentType":{"attributes":{"term":"Application", "label":"Aplicativo"}}, "rights":{"label":"© Facebook, Inc."}, "title":{"label":"Messenger - Facebook, Inc."}, "link":{"attributes":{"rel":"alternate", "type":"text/html", "href":"https://itunes.apple.com/br/app/messenger/id454638411?mt=8&uo=2"}}, "id":{"label":"https://itunes.apple.com/br/app/messenger/id454638411?mt=8&uo=2", "attributes":{"im:id":"454638411", "im:bundleId":"com.facebook.Messenger"}}, "im:artist":{"label":"Facebook, Inc.", "attributes":{"href":"https://itunes.apple.com/br/artist/facebook-inc./id284882218?mt=8&uo=2"}}, "category":{"attributes":{"im:id":"6005", "term":"Social Networking", "scheme":"https://itunes.apple.com/br/genre/ios-redes-sociais/id6005?mt=8&uo=2", "label":"Redes sociais"}}, "im:releaseDate":{"label":"2011-10-19T15:39:30-07:00", "attributes":{"label":"19/10/2011"}}}, n{"im:name":{"label":"WhatsApp Messenger"}, "im:image":[n{"label":"https://m.xsw88.com/allimgs/daicuo/20230905/1221.png", "attributes":{"height":"53"}}, n{"label":"https://m.xsw88.com/allimgs/daicuo/20230905/1222.png", "attributes":{"height":"75"}}, n{"label":"https://m.xsw88.com/allimgs/daicuo/20230905/1223.png", "attributes":{"height":"100"}}], "summary":{"label":"O WhatsApp Messenger é um mensageiro para smartphone
09-10 20:04:03.013  18211-18241/com.yuretsrodik.top100apps W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x42044e48)
09-10 20:04:03.023  18211-18241/com.yuretsrodik.top100apps E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.yuretsrodik.top100apps, PID: 18211
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.yuretsrodik.top100apps.AsyncTaskParseJson.doInBackground(AsyncTaskParseJson.java:32)
            at com.yuretsrodik.top100apps.AsyncTaskParseJson.doInBackground(AsyncTaskParseJson.java:10)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

就会显得很thanksful的帮助!因为我真的栈(

Will be very very thanksful for the help!! Cuz I'm really stack(

推荐答案

由于 njzk2 的意见,以避免使用 JSONParser ,所以我做了所有我很短的时间内需要和较少的努力。 我需要获得root 的JSONObject - 的的的iTunes 的应用程序名称。 并将其插入到数据库中。 这是该方法 doInBackground AsyncTask.class

Thanks to njzk2 for the advice to avoid using JSONParser, so I've made all I needed in very shorter time and with less efforts. I needed to get root JSONObject - names of applications in iTunes. and insert it into database. This is the full code of the method doInBackground in AsyncTask.class

@Override
    protected Boolean doInBackground(Void... params) {
        Log.d(LOG, "AsyncTask. Do in background");
        ContentValues cv = new ContentValues();

        try {//Making a request to server getting entities
            JSONObject json = new JSONObject(EntityUtils.toString(
                    new DefaultHttpClient().execute(
                            new HttpGet(url)).getEntity()));
            //getting json root object
            JSONObject feedObject = json.getJSONObject("feed");
            //getting needed array in root json object
            JSONArray entryArray = feedObject.getJSONArray("entry");

            //moving though the array
            for(int i = 0; i < entryArray.length(); i++){
                //getting all objects in array
                JSONObject entryObjects = entryArray.getJSONObject(i);
                //taking objects with needed key
                JSONObject nameObject = entryObjects.getJSONObject("im:name");
                //getting string name
                String name = nameObject.getString("label");
                //putting data into ContentValues - name and id (for making a numbers
                // next to records in ListView)
                cv.put(DB.COL_NAME, name);
                cv.put(DB.COL_ID, i+1);
                mDB.insert(cv);
                //just controlling in log
                Log.d(LOG, "" + name);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }