我的php脚本将此字符串返回到我的Android应用程序:
[{"id":"61","device":"a914a24d2352646","lat":"59.864650963824815","lng":"18.150743767619133","comment":"Kkkk","image":null},
{"id":"62","device":"a914a24d2352646","lat":"59.86462319043523","lng":"18.150545619428158","comment":"Jj","image":null}]
要返回此数据,我只需执行echo
结果。在我的java代码中,我喜欢这样来接收这些数据:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_FETCH_ALERT);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
现在我如何使用此字符串创建一个真正的数组,以便更简单地使用它?或者我可以用另一种方式从我的php sctipt中获取某种类型的数组对象吗?
答案 0 :(得分:1)
该格式以JSONArray形式出现,因此您将创建一个JSONArray对象,然后循环遍历它并拉出JSONObjects。
JSONArray jsonArr= new JSONArray(response);
for(int i=0;i<jsonArr.length();i++){
JSONObject json=jsonArr.getJSONObject(i);
//Do whatever you want with that item's data via json.getString('key')
// or json.getInt('key) etc...
}
答案 1 :(得分:0)
最简单的方法是创建一个Java类,它匹配您编码为JSON的原始类/数组,例如:
public class Obj{
private long id = 0;
private String device = "";
.... etc
}
然后,使用Gson(或JSON,无论您喜欢哪种方式)将返回的字符串转换为您的对象,例如:
Obj o = new Gson().fromJson(YOURSTRING, Obj.class);
然后您可以正常访问您的对象。显然你必须修改数组,但你应该明白:)希望这会有所帮助!