用PHP解析JSON POST请求

我在java中生成了一个包含JSON对象的HTMLPost请求,并希望在PHP中解析它。

public static String transferJSON(JSONObject j) { HttpClient httpclient= new DefaultHttpClient(); HttpResponse response; HttpPost httppost= new HttpPost(SERVERURL); List nameValuePairs = new ArrayList(2); nameValuePairs.add(new BasicNameValuePair("json", j.toString())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); } 

并在服务器上

 <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // input = "json=%7B%22locations%22%3A%5B%7B%22..." $input = file_get_contents('php://input'); // jsonObj is empty, not working $jsonObj = json_decode($input, true); 

我想这是因为JSON特殊字符是编码的。

json_decode返回空响应

知道为什么吗?

您实际上是使用单个值对json =(编码的json)发布HTTP表单实体( application/x-www-form-urlencoded ),而不是POST一个application/json实体。

代替

 List nameValuePairs = new ArrayList(2); nameValuePairs.add(new BasicNameValuePair("json", j.toString())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

尝试

  httppost.setEntity(new StringEntity(j.toString(),"application/json","UTF-8")); 

这是设计的:您正在访问原始POST数据,需要对其进行URL编码。

首先在数据上使用urldecode()

尝试这个:

 //remove json= $input = substr($input, 5); //decode the url encoding $input = urldecode($input); $jsonObj = json_decode($input, true);