- 我知道解析,我已经成功解析了下面的数据,但是当web服务升级时,我需要解析对象内的对象。 - 我尝试了许多例子,但收到了错误。
解析代码:
private final String KEY_SUCCESS = "status";
private final String KEY_MSG = "Message";
private final String KEY_MSG1 = "Message";
// private final String KEY_AddressList = "addressList";
private final String KEY_USERINFO = "user_info";
ArrayList<HashMap<String, String>> arraylist;
private final String KEY_DATA = "data";
private final String KEY_USERDATA = "userdata";
public ArrayList<HashMap<String, String>> getList(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
arraylist = new ArrayList<HashMap<String, String>>();
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonArray.getJSONObject(i);
// JSONObject job = obj.getJSONObject("User");
Log.d("obj", obj.toString());
String user_id = obj.getString(Constants.Params.ID);
String createdate = obj.getStringAndyConstants.Params.CREATEDDATE);
String postImage = obj.getString(Constants.Params.IMAGE);
map.put(AndyConstants.Params.ID, user_id);
map.put(AndyConstants.Params.CREATEDDATE, createdate);
map.put(AndyConstants.Params.IMAGE, postImage);
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
for (int j = 0; j < jsonArrayUser.length(); j++) {
HashMap<String, String> mapUser = new HashMap<String, String>();
JSONObject businessObject = jsonArrayUser.getJSONObject(j);
Log.d("obj", businessObject.toString());
}
Log.d("map", map.toString());
arraylist.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return arraylist;
}
错误日志:
org.json.JSONException: No value for data
E/array: []
E/adapter: []
杰森:
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}
答案 0 :(得分:1)
你不需要这一行
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
并更改
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
到
JSONObject userData = obj.getJSONObject("userdata");
String firstName = userData.getString("first_name");
String lastName = userData.getString("last_name");
正如您从JSON中看到的那样
"data":
[{"user_id":"46",
"image":"",
"createdate":"2016-05-11 06:05:12",
"userdata":{"first_name
数据具有对象[表示数组,而userData显示{是JSONObject
答案 1 :(得分:0)
我注意到你的JSON有一些错误。这是完整的Json响应吗?
因为JSON响应应该是这样的:
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}]
}
您会注意到Json中[
之后userdata
没有关闭。