2016-05-04 2 views
0

В андроид-студии я пытаюсь разобрать данные JSON в приложении для Android. Для этого я написал этот код (приведенный ниже). Но этот код бросает org.json.JSONException. На самом деле я хочу вывода, как это:org.json.JSONException в Android во время анализа данных JSON

/*This is just a sample*/ 
ROW: 1 
id = ### 
date = 0/0/0 
latitude = 12.123456789 
longitude = 12.123456789 
description = any note 

Мой код:

String jsonData = "["+ 
         "{ "_id" : { "$oid" : "57###ad"} , "document" : { "date" : "3/8/2016" , "latitude" : "33.63043627520588" , "longitude" : "72.95956905931234" , "description" : "note-1"} , "safe" : true} , "+ 
         "{ "_id" : { "$oid" : "57###65"} , "document" : { "date" : "7/7/2017" , "latitude" : "33.647092700303" , "longitude" : "72.99582783132792" , "description" : "note-2"} , "safe" : true} "+ 
        "]"; 

JSONObject jsonRootObject = new JSONObject(jsonData); 
//Get the instance of JSONArray that contains JSONObjects 
JSONArray jsonArray = jsonRootObject.optJSONArray("document"); 
//Iterate the jsonArray and print the info of JSONObjects 

for(int i=0; i < jsonArray.length(); i++) { 
    JSONObject jsonObject = jsonArray.getJSONObject(i); 
    String date = jsonObject.optString("date").toString(); 
    String latitude = jsonObject.optString("latitude").toString(); 
    String longitude = jsonObject.optString("longitude").toString(); 
    String description = jsonObject.optString("description").toString(); 
    String id = jsonObject.optString("id").toString(); 

    result += "ROW"+i+" : \n id= "+ id + \n date= "+ date +" \n latitude= "+ latitude+" \n longitude= "+ longitude +" \n "; 
} 

Log.d("RESULT:",result); 

Ошибка

05-04 23:56:48.475 9762-11393/com.example.abc.project1 E/Error: Exception 
                   org.json.JSONException: Value [{"_id":{"$oid":"57###ad"},"safe":true,"document":{"date":"3\/8\/2016","description":"note-1","longitude":"72.95956905931234","latitude":"33.63043627520588"}},{"_id":{"$oid":"57###65"},"safe":true,"document":{"date":"7\/7\/2017","description":"note-2","longitude":"72.99582783132792","latitude":"33.647092700303"}}] of type org.json.JSONArray cannot be converted to JSONObject 
at org.json.JSON.typeMismatch(JSON.java:111) 
at org.json.JSONObject.<init>(JSONObject.java:158) 
at org.json.JSONObject.<init>(JSONObject.java:171) 
at com.example.abc.project1.MongoHQ.ReadDB.doInBackground(ReadDB.java:68) 
at com.example.abc.project1.MongoHQ.ReadDB.doInBackground(ReadDB.java:32) 
at android.os.AsyncTask$2.call(AsyncTask.java:287) 
at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
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:838) 

ответ

2

Вы не правильно разбора строки JSON в соответствии с его структурой. Ваша строка json - это массив, и вы рассматриваете его как JSONObject.

Попробуйте это -

JSONArray jsonRootObject = null; 

try { 
    jsonRootObject = new JSONArray(jsonData); 

    //Get the instance of JSONArray that contains JSONObjects 

    //Iterate the jsonArray and print the info of JSONObjects 

    for(int i=0; i < jsonRootObject.length(); i++) { 

     JSONObject jsonObject = jsonRootObject.getJSONObject(i); 

     JSONObject docObject = jsonObject.getJSONObject("document"); 
     JSONObject idObject = jsonObject.getJSONObject("_id"); 

     String date = docObject.optString("date").toString(); 
     String latitude = docObject.optString("latitude").toString(); 
     String longitude = docObject.optString("longitude").toString(); 
     String description = docObject.optString("description").toString(); 
     String id = idObject.optString("$oid").toString(); 


     result += "ROW"+i+" : \n id= "+ id + "\n date= "+ date +" \n latitude= "+ latitude+" \n longitude= "+ longitude +" \n "; 
    } 

    Log.d("RESULT:",result); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
1

Если она начинается с брекетами {} это объект; если он начинается с скобок [], это массив. Ваш jsonData не является объектом JSON, это массив JSON, поэтому его нельзя отнести к JSONObject.

Изменить это:

JSONObject jsonRootObject = new JSONObject(jsonData); 
//Get the instance of JSONArray that contains JSONObjects 
JSONArray jsonArray = jsonRootObject.optJSONArray("document"); 

Для этого:

JSONArray jsonArray = new JSONArray(jsonData); 

И вы должны быть хорошо.


я заметил еще несколько вопросов в структуре вашей десериализации следующий цикл должен работать:

JSONArray jsonArray = new JSONArray(jsonData); 

for(int i = 0; i < jsonArray.length(); i++) { 
    JSONObject jsonObject = jsonArray.getJSONObject(i); 

    JSONObject idObject = jsonObject.getJSONObject("_id"); 
    JSONObject document = jsonObject.getJSONObject("document"); 

    String id = idObject.optString("$oid"); 
    String date = document.optString("date"); 
    String latitude = document.optString("latitude"); 
    String longitude = document.optString("longitude"); 
    String description = document.optString("description"); 
    Boolean safe = jsonObject.optBoolean("safe"); 

    result += // your code here 
} 
+0

ваш код не компилируются как 'JSONArray jsonArray = jsonRootObject.optJSONArray («документ»); 'неверно, так как« document »не является массивом –

+0

@ShadabAnsari Прошу прощения, если мой ответ был неясным, но я говорил заменить первый блок кода на второй, поэтому' JSONArray jsonArray = jsonRootObject.optJSONArray («document») 'больше не будет в коде. Я заметил некоторые другие ошибки в исходном коде и изменил свой ответ, чтобы это отразить. Я только сейчас заметил, что он почти точно соответствует вашему ответу ... ха-ха. – Bryan

Смежные вопросы