【问题标题】:Parse escaped JSON in PHP在 PHP 中解析转义的 JSON
【发布时间】:2012-08-25 23:30:38
【问题描述】:

我是 PHP 世界的新手,在 PHP 中解析 JSON 时遇到问题。我想使用我的 Java 客户端使用 Apache HttpClient 4.xGson 将数据发布到 PHP 脚本。

我的 JSON:

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

我使用 HttpClientGson 使用 Java 发送它:

    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");

在页面上:

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

我得到的是:

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

我怎样才能让它工作?

PHP 5.2 - 不能使用json_last_error()

【问题讨论】:

  • 如果您使用的是 php 5.2,那么您就有问题了。它不再受支持。 5.3 中修复了许多在 5.2 中仍然存在的安全问题,因此您基本上是在面向公众的系统上使用不安全的软件。是时候升级了,我的朋友。
  • 很难确定问题出在哪里。您提供的 json 字符串部分看起来不错,但我需要看到整个想法。只需要一个不匹配的括号、引号或逗号就可以将整个内容扔掉。在您向我们展示的代码中看不到任何内容,但这并不意味着它不存在。

标签: java php json parsing apache-httpclient-4.x


【解决方案1】:

试试stripslashes()

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

我会的

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-16
    • 2012-01-21
    • 2021-09-18
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多