2015-02-05 53 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

相关问题