在PHP中接收JSONObject

时间:2014-04-18 16:39:58

标签: php android json

我使用下面的代码将JSONObject发送到服务器。但我无法使用PHP在服务器端接收它。任何人都可以指导我如何收到它。

public void sendStatus(JSONObject object) {


        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 10000);
        HttpClient httpclient = new DefaultHttpClient(myParams);
        String jsonString = object.toString();

        try {

            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Content-type", "application/json");

            StringEntity se = new StringEntity(jsonString); 
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httppost.setEntity(se); 

            HttpResponse response = httpclient.execute(httppost);
            String temp = EntityUtils.toString(response.getEntity());


        } catch (ClientProtocolException e) {

        } catch (IOException e) {
        }
}

我已经使用以下代码

使用名称值对完成了它
$datastring = trim($headers['name']);

但是在上面的代码中,我只获取JSONObject而不是任何标记。所以,任何人都可以帮助我或提供任何有用的链接,那么我将不胜感激。

我的JSONObject格式为belos = w

{
  "user_id": "123456",
  "Objects": [
    {
      "name": "AAA"
    },
    {
      "name": "BBB"
    },
    {
      "name": "CCC"
    },
    {
      "name": "DDD"
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

要从Android设备发送JSON作为字符串,您可以将其作为POST参数发送:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json_string", jsonString)); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

或者如果您想将其作为标题发送:

httppost.addHeader("json_string", jsonString)

但是,标题有最大长度,所以我建议将其作为POST参数发送

为了在PHP中使用JSON对象,您必须先将其解码为执行以下操作的关联数组

$jsonAsArray = json_decode($jsonAsString, true)

之后,您将能够访问JSON属性,如:

$jsonAsArray['user_id']                // 123456
$jsonAsArray['Objects'][1]['name']     // BBB