我正在为我的项目使用Android 5.1,然后我尝试从我的服务器返回json文件,它给我这样的结果:
[
{
"id": 3,
"title": "asdiasjdaklsj",
"description": "dfkldjskdhjsfkldjsfkl",
"owner": "kyaaa",
"start": "01/27/2016 12:00 AM",
"end": "01/28/2016 12:01 AM"
}
]
可以用于android的结果是这样的:
"employees":[
{"id":"John", "title":"Doe"},
{"id":"Anna", "title":"Smith"},
{"id":"Peter","title":"Jones"}
]
上面的Json是我使用的代码中的工作结果,但是当我转向我自己的Json时,它将返回错误,应用程序将停止工作。我想知道那是什么问题。
package net.simplifiedcoding.volleysample;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Belal on 9/22/2015.
*/
public class ParseJSON {
public static String[] ids;
public static String[] titles;
public static String[] descriptions;
public static String[] owners;
public static String[] starts;
public static String[] ends;
public static final String JSON_ARRAY = "result";
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_OWNER = "owner";
public static final String KEY_START = "start";
public static final String KEY_END = "end";
private JSONArray users = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
titles = new String[users.length()];
descriptions = new String[users.length()];
owners = new String[users.length()];
starts = new String[users.length()];
ends = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
titles[i] = jo.getString(KEY_TITLE);
descriptions[i] = jo.getString(KEY_DESCRIPTION);
owners[i] = jo.getString(KEY_OWNER);
starts[i] = jo.getString(KEY_START);
ends[i] = jo.getString(KEY_END);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
然后应用程序没有工作并停止工作,然后我发现问题是这样的。我的服务器不会将json数组返回给我,但在android工作室内,它需要jsonarray,因此可以执行将数据拉到我的手机。可以任何人告诉我的是,任何其他方式可以拉出没有json数组的数据吗?谢谢
答案 0 :(得分:0)
在json []中表示数组,而{}表示对象。您应该首先使用JsonArray,然后您将能够迭代对象。
答案 1 :(得分:0)
您的服务器响应似乎是一个数组,而不是一个对象,尝试进行此更改,而不是将其转换为JSONObject,然后尝试从中获取JSONArray。
JSONArray users = new JSONArray(json);
希望它有所帮助!