java – Android应用程序的JSON编码数据

我正在尝试将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,你应该很高兴.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...