Parse escaped JSON in PHP

随声附和 提交于 2019-12-01 10:08:46

问题


I'm a newb in PHP world and I've problems parsing JSON in PHP. I want to POST data to PHP script with my Java client using Apache HttpClient 4.x and Gson.

My JSON:

[{"Knt_KntWatchId":"15","type":"INSERT","Knt_Nazwa1":"a"},{...},...]

I'm sending it with Java using HttpClient and Gson:

    List<Contact> contacts = ...;
    HttpPost post = new HttpPost(CONTACTS_SERVICE);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("key", AppConstants.KEY));
    nameValuePairs.add(new BasicNameValuePair("data", new Gson().toJson(contacts)));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

On page:

if (isset($_POST['data'])) {
    $data = $_POST['data'];
    $json = json_decode($data, true);
    var_dump($json);
    var_dump($data);

What I'm getting is:

NULL string(3651) "[{\"Knt_KntWatchId\":\"15\",\"type\":\"INSERT\",\"Knt_Nazwa1\":\"a\"},...

How can I get it working?

PHP 5.2 - can't use json_last_error()


回答1:


try with stripslashes()

$string = stripslashes('[{\"Knt_KntWatchId\":\"15\",\"type\":\"INSERT\",\"Knt_Nazwa1\":\"a\"}]');
print_r(json_decode($string));

so il will be

$json = json_decode(stripslashes($data), true);


来源:https://stackoverflow.com/questions/12210398/parse-escaped-json-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!