2015-02-05 42 views
0

我從我在我通過服務,並以發送到我的活動Android應用程序服務器獲得一個JSONObject我轉換的JSONObject的字符串JSONException而轉換成JSONArray

String myjson= gson.toJson(object); 
b.putString("json", myjson); 

和字符串傳遞給我的活動在這裏我從字符串重新創建JSONObject的

Gson gson = new Gson(); 
JSONObject jobj = gson.fromJson(mydata, JSONObject.class); 
JSONArray jarray = jobj.getJSONArray("myitems"); 

我的JSON是如下

{"myitems":[{"event_id":"1","title":"Music launch party at makeover","description":"Music Launch function at Makeover","store_id":"2","user_id":"1","category_id":"1","submittedby":"store","start_date":"2015-02-03 09:00:01","end_date":"2015-02-03 20:00:00","price":"1000","gallery_1":"","gallery_2":"","gallery_3":"","add_lat":"30.693771","add_lon":"76.76486","distance":"10.329089177806534"},{"event_id":"2","title":"The Bacardi party at the New year bash","description":"Altius organizes a new year bash at their Night House.","store_id":"2","user_id":"1","category_id":"3","submittedby":"user","start_date":"2015-02-05 17:08:40","end_date":"2015-02-05 22:08:48","price":"2000","gallery_1":"","gallery_2":"","gallery_3":"","add_lat":"30.69461","add_lon":"76.76176","distance":"10.575941394542852"}]} 

但是我得到jsonobject jsonarray錯誤。從jsonobject獲取jsonarray的正確方式是什麼或者我在這裏做了什麼錯誤。

+0

什麼錯誤說? – TZHX 2015-02-05 16:24:04

+0

jsonexception .gson.internal.LinkedTreeMap無法轉換爲jsonarray – user2779311 2015-02-05 16:28:38

+1

這裏有一些建議,我從網上搜索JSON操作,當在嵌套的對象或數組在JSON嘗試正確地使映射類,然後做你的工作。 – 2015-02-05 16:37:35

回答

2

嘗試以下操作:

  1. 創建包含JSON的副本的類的對象

     
    public class MyItem {

    String event_id; String title; String description; String store_id ; String user_id; String category_id; String submittedby; String start_date; String end_date; String price; String gallery_1; String gallery_2; String gallery_3; String add_lat; String add_lon; String distance;

    public MyItem() { } }

  2. In your case myjson is the string containing the json reply..so

     JSONArray array = null; 
    
         try { 
          JSONObject jsonResp = new JSONObject(myjson); 
          array = jsonResp.getJSONArray("myitems"); 
    
         } catch (JSONException e) { 
    
          e.printStackTrace(); 
         } 
    
  3. 然後你就可以通過自定義類的陣列和存儲對象,像這樣重複:

for(int i = 0; i < array.length(); i ++){ JSONObject json2 = null;

try { json2 = (JSONObject) array.get(i); } catch (JSONException e) { e.printStackTrace(); } Gson gson = new Gson(); MyItem myItem = gson.fromJson(json2.toString(), MyItem.class); //Do whatever you want with the object here

}

+0

如果我不使用gson將字符串轉換回jsonobject,並按照你寫的,我得到錯誤獲取jsonarray沒有價值myitems.kindly更新 – user2779311 2015-02-05 17:03:49

+0

其因爲你沒有映射json對象到一個自定義類...試試我的例子它的工作原理...我測試了它 – 2015-02-05 17:05:45

+0

這是標題欄的logcat:myITEM:音樂發佈會在改造 – 2015-02-05 17:11:27

相關問題