为了将 json 从 android 发布到 php,我使用了 Volley 库 StringRequest
对象。
StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// some code
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//some code
}
}){
@Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
ArrayList<Command> commands = MyApplication.readFromPreferences(getActivity(), Constants.COMMAND);
String jsonCommands = new Gson().toJson(commands);
params.put("commands", jsonCommands);
return params;
}
};
为了在 php 中捕获数据并验证它是否被正确发送,我使用了这个
echo $_POST["commands"];
输出:
[{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"CF77 COIN FINDER\",\"url_image\":\"IMG_76ECDC-707E7E-70AC81-0A1248-4675F3-F0F783.jpg\",\"name\":\"CF77 COIN FINDER\",\"pid\":12,\"price\":500.0},\"product_quantity\":3},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"JEOSONAR 3D DUAL SYSTEM\",\"url_image\":\"IMG_2D9DF0-2EB7E9-ED26C0-2C833B-B6A5C5-5C7C02.jpg\",\"name\":\"JEOSONAR 3D DUAL SYSTEM\",\"pid\":15,\"price\":500.0},\"product_quantity\":1},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"MAKRO POINTER\",\"url_image\":\"IMG_Macro.jpg\",\"name\":\"MAKRO POINTER\",\"pid\":18,\"price\":500.0},\"product_quantity\":3}]
我注意到当使用 Volley 库通过 POST 方法发送 json 字符串时,添加了很多反斜杠来转义双引号。
我的问题来了:
我想在 php 中将 json 解码为对象数组,所以我使用了
$commands = json_decode( $_POST["commands"],true);
但由于 json 上面的无效(由反斜杠引起),它总是返回一个空数组。
在php或java SDK中是否有一种方法提供发送和接收json的契约(Contract)而不会出现此类问题?或者我应该在 php 中重新格式化 json 并删除所有反斜杠?
最佳答案
问题是您尝试在 URL 参数中发送 json 数据。
您需要覆盖 getBody()
方法以将 json 数据作为请求主体而不是 url 参数返回。
例如:
/**
* Returns the raw POST or PUT body to be sent.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
return new Gson().toJson(commands).getBytes();
}
然后在 PHP 中您可以:
$jsonRequest = json_decode(stream_get_contents(STDIN));
关于java - 如何将 json 从 android 发送到 php?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31024436/