【问题标题】:with java encoded json string fails to decode with php使用 java 编码的 json 字符串无法使用 php 解码
【发布时间】:2017-06-14 12:06:35
【问题描述】:

我真的很难用 Java 和 PHP 编码字符串。
我使用 Java 来管理 Wordpress 中的帖子。为此,我在 JavaFX 中创建了一个 GUI,并扩展了 REST-API 以创建 SEO 插入。 Worpdress 数据库使用 utf8_general_ci 编码。
我通过 Post 将数据作为 JSON 编码的字符串发送到 WP-Api。我使用 org.JSON。用于 Java 中的解码/编码。
我试图用 php 解码 json-string,

json_decode($request->get_param('data'), true);

但我收到以下错误:

UTF-8 格式错误,可能编码不正确

所以我尝试用php转换它

$s = iconv("Windows-1252", "UTF-8", $s);

它有效,但像“ä,ö,ü,ß”等字符只是显示为 ü, Ã,...

接下来我尝试用 Java 对其进行编码,如此处所述Converting Java String From/to utf-8

private String convertToUTF8(String s) {
    String out = null;
    try {
        out = new String(s.getBytes("UTF-8"), "ISO-8859-1");
    } catch (java.io.UnsupportedEncodingException e) {
        return null;
    }
    return out;
}

但是有了这个并且没有“iconv”它又失败了。

我做错了什么,我该如何解决?

服务器运行php7.0。我将 jdk1.8.0_66 用于 Java。

【问题讨论】:

  • 您的 convertToUTF8 没有“转换”它“转换”的 UTF-8 来自 UTF-8
  • @Tom 不,它甚至没有这样做。它将字符串导出为“UTF-8”表示,然后将其导入为“ISO-8859-1”,因此会产生一些垃圾。

标签: java php json utf-8 character-encoding


【解决方案1】:

使用String 对象分配加密是一个常见错误。 Strings 应该是对编码等实现细节的抽象。只要您只使用Strings,您只需要知道它们是Unicode。仅当您将 String 转换为字节时,特定编码才会起作用,在您的情况下,这可能意味着在某些 HTTP 客户端中。我不知道你用什么,所以我附上了一个来自 Apache 的示例。

public void sendMessage(CloseableHttpClient client, String endpointUrl, String jsonString) throws IOException {
    HttpPost post = new HttpPost(endpointUrl);
    post.addHeader("Content-Type", "application/json; charset=utf-8"); // Apache would probably set it for you, but since I'm not 100% sure, I added it here.
    post.setEntity(new StringEntity(jsonString, ContentType.create("application/json", Consts.UTF_8))); // here the actual conversion takes place and only here do you need to worry about encoding
    try (CloseableHttpResponse response = client.execute(post)) {
        // act on response here
    }
}

备注1:这个例子就是这样:一个例子,用来说明一个观点。我没有测试过,对Apache HTTP客户端不是很了解,所以要小心。

备注2:看来你可以用ContentType APPLICATION_JSON代替ContentType.create("application/json", Consts.UTF_8)——它默认使用UTF-8。但在你的问题的背景下,这种方式似乎更清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2015-02-25
    • 2012-08-24
    • 2012-05-27
    • 1970-01-01
    • 2013-04-24
    • 2021-10-26
    相关资源
    最近更新 更多