4

I'm trying to send JSON data from a php script to an Android app and the php script's output is different from what the Java app expects.

$data['sample']['txt']="hello world";
echo json_encode($data) // {"sample":{"txt":"hello world"}}
//above is incorrect, need {sample : [{txt:"hello world"}]}

The incorrect format results in the following Java exception:

org.json.JSONException: Value {"txt":"hello world"} at sample of type org.json.JSONObject cannot be converted to JSONArray.  

Is there an argument of PHP's json_encode that I'm missing, or an alternative that would encode it properly?

Java code for async task:

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) just sets the value to a TextView, which is where the error is displaying. (or the response if I hard code the echo statement)

Solution:

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*
}
4

2 回答 2

4

您展示的两个 JSON 示例都是有效的 JSON,这只是您的映射在每一端的问题。

您的 java 代码期望“样本”包含一个对象集合(列表或数组),其中每个对象都有一个 txt 字段。这就是为什么它在 JSON 中的对象值周围有 []。

您可以更改 java 端的映射以仅期望 sample 的单个值,或者您可以更改 php 代码,使 $data['sample'] 是一个具有单个元素的数组,该元素具有 'txt' = "hello world" .

如果您在 java 端包含映射,我可以提供帮助。如果您想在 php 端修复它,我相信一些 php 大师可以提供帮助。

编辑:

JSONArray JSONarr=JSONobj.getJSONArray("sample");要求一个数组。将其更改为 JSONObject,您应该一切顺利。

于 2013-01-03T20:50:19.320 回答
-1

解决问题的一种方法是执行以下操作...

<?php
    $json = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9]*)":/', '$1:', json_encode($whatever));
?>

虽然我怀疑问题出在你的 Java/Dalvik 代码上,因为你得到的 JSON 是完全合法的。查看JSON-RPC 2.0 规范中的示例。

此页面上还有一个特定的 Android 示例也符合规范:

{"hash":{"attribute":"123"},"attribute":"value", …}
于 2013-01-03T20:42:06.680 回答