Java Android应用程序的JSON编码数据

Java Android应用程序的JSON编码数据,java,php,json,Java,Php,Json,我试图将JSON数据从php脚本发送到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.JSONExcep

我试图将JSON数据从php脚本发送到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);
    }

}

公共类RetrieveData扩展AsyncTask解决问题的一种方法是执行以下操作

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

您展示的两个JSON示例都是有效的JSON,只是两端的映射是什么的问题

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

您可以在java端更改映射,使sample只需要一个值,也可以更改php代码,使$data['sample']是一个包含单个元素的数组,该元素的“txt”=“hello world”

如果您在java端包含映射,我可以提供帮助。如果您想在php方面解决它,我相信一些php专家会提供帮助

编辑:


JSONArray-JSONarr=JSONobj.getJSONArray(“示例”)正在请求数组。将其更改为JSONObject,您就可以开始了。

问题在于您没有正确使用java库。当然,你可以使用php代码来修补这个问题。带引号的变体是正确的,我怀疑Android弄错了。我认为问题更多的是关于缺少方括号的抱怨。当我用echo“{sample:[{txt:\'helloworld\'}]}”替换echo语句时;Android应用程序接受了这些值。你是对的,缺少方括号是个问题。有关详细信息,请参阅我的答案。您应该了解JSON的格式,以便将来可以轻松地调试类似的问题。这里有一个简单的入门。很高兴你让它工作,并感谢更新与工作的解决方案。你知道的。。。为了孩子!另一方面,如果您打算使用JSON做更多的琐碎工作,我建议您使用类似Jackson的JSON映射库。
<?php
    $json = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9]*)":/', '$1:', json_encode($whatever));
?>
{"hash":{"attribute":"123"},"attribute":"value", …}