我正在尝试将PHP脚本中的JSON数据发送到Android应用程序,并且PHP脚本的输出与Java应用程序所期望的不同.
$data['sample']['txt']="hello world";
echo json_encode($data) // {"sample":{"txt":"hello world"}}
//above is incorrect, need {sample : [{txt:"hello world"}]}
格式不正确会导致以下Java异常:
org.json.JSONException: Value {"txt":"hello world"} at sample of type org.json.JSONObject cannot be converted to JSONArray.
是否存在我缺少的PHP json_encode的参数,或者是否可以正确编码它?
异步任务的Java代码:
public class RetrieveData extends AsyncTask<List<? extends NameValuePair>, Integer, List<String>> {
protected List<String> doInBackground(List<? extends NameValuePair>... postData) {
InputStream is = null;
List<String> result = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.72.2:10088/droid_test/test.PHP");
httppost.setEntity(new UrlEncodedFormEntity(postData[0]));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
reader.close();
is.close();
JSONObject JSONobj=new JSONObject(sb.toString());
JSONArray JSONarr=JSONobj.getJSONArray("sample");
for(int i = 0 ; i < JSONarr.length() ; i++){
result.add(JSONarr.getJSONObject(i).getString("txt"));
}
}
catch(Exception e) {
result.add("ERROR "+e.toString());
}
return result;
}
protected void onPostExecute(List<String> result) {
getHTTP(result);
}
}
getHTTP(result)只是将值设置为TextView,这是显示错误的位置. (如果我对echo语句进行硬编码,则为响应)
解:
JSONObject JSONobj=new JSONObject(sb.toString());
JSONObject JSONarr=JSONobj.getJSONObject("sample"); // made object per @digitaljoel's suggestion
for(int i=0; i<JSONarr.length(); i++) {
result.add(JSONarr.getString("txt")); // getting a String, not another array/object *duh*
}
解决方法: 您展示的两个JSON示例都是有效的JSON,这只是您的映射在每一端的问题.
您的Java代码期望“sample”包含对象的集合(列表或数组),其中每个对象都有一个txt字段.这就是为什么它在JSON中的对象值周围有[].
您可以更改java端的映射以期望只有一个示例值,或者您可以更改PHP代码,以便$data [‘sample’]是一个包含’txt’=“hello world”的单个元素的数组.
如果你在java方面包含映射,我可以帮忙.我敢肯定,如果你想在PHP端修复它,一些PHP大师可以提供帮助.
编辑:
JSONArray JSONarr = JSONobj.getJSONArray(“sample”);正在要一个阵列.将其更改为JSONObject,你应该很高兴. (编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|