我通过服务在Android应用程序中从我的服务器获取JSONObject,为了发送到我的活动,我将JSONObject转换为带有
的字符串String myjson= gson.toJson(object);
b.putString("json", myjson);
将字符串传递给我的活动,我从String重新创建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 :(得分:2)
尝试以下方法:
创建一个包含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() { } }
在你的情况下,myjson是包含json reply..so
的字符串 JSONArray array = null;
try {
JSONObject jsonResp = new JSONObject(myjson);
array = jsonResp.getJSONArray("myitems");
} catch (JSONException e) {
e.printStackTrace();
}
然后你可以遍历数组并在自定义类中存储对象,如下所示:
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
}