【问题标题】:MOXy not able to marshall UTF-8 characters correctly with application/jsonMOXy 无法使用 application/json 正确编组 UTF-8 字符
【发布时间】:2015-02-23 16:49:08
【问题描述】:

我真的被 Eclipselink MOXy 2.5.1 卡住了,没有为我提供正确编码的亚洲字符(或其他字符,例如德语变音符号 äöü)。

我的代码:

@GET
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8"})
@Path("/test")
public Response getJson() throws IOException{
    return Response.ok(new Test()).build();
}

@GET
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8"})
@Path("/test2")
public Response getKey() throws IOException{
    return Response.ok(new Test().toString()).build();
}

Test 类如下所示:

@XmlRootElement
class Test{

   public String key;

   public Test() throws IOException {
       key = FileUtils.readFileToString(new File("e:\\utf8.txt"), "UTF-8");
   }

   public String toString() {
       return key;
   }
}

为了测试目的,属性“key”仅使用一个字符串进行初始化,该字符串是我从一个不包含 BOM 的 UTF-8 编码文件中读取的

アナログカメラは

当我通过客户端调用这两种资源时:

    Client client = ClientBuilder.newClient();
    WebTarget webTarget = client.target("http://127.0.0.1/rest").path("/test");
    WebTarget webTarget2 = client.target("http://127.0.0.1/rest").path("/test2");

    Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON_TYPE);
    invocationBuilder.header(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
    Response response = invocationBuilder.get();
    System.out.println("Result /test: " + response.readEntity(String.class));

    invocationBuilder = webTarget2.request(MediaType.APPLICATION_JSON_TYPE);
    invocationBuilder.header(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
    response = invocationBuilder.get();
    System.out.println("Result /test2: " + response.readEntity(String.class));

我得到以下结果:

Result /test: {"key":"��?��o"}
Result /test2: アナログカメラは

奇怪的是,当我在 /test2 中编组测试对象的 toString() 方法时会返回正确编码的字符,而使用 /test 编组测试对象不会。

有什么想法吗?我有点迷路了。

【问题讨论】:

    标签: json encoding utf-8 jaxb moxy


    【解决方案1】:

    很抱歉,我必须解决这个问题。解决方案是使用最新的稳定 MOXy 库 2.5.2。这解决了我的问题,就像一个魅力(幸运的我)。好的,就在几分钟前,我问了这个问题,但请确保我是在过去几天以来绝望地寻找解决方案后发布的。 我得到的唯一提示是https://bugs.eclipse.org/bugs/show_bug.cgi?id=419072#attach_236300,但这只是提到了控制字符的奇怪行为。

    希望这可以帮助遇到同样问题的任何人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2011-08-09
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      相关资源
      最近更新 更多