java json utf-8_java-球衣Web服务json utf-8编码

java-球衣Web服务json utf-8编码

我使用Jersey 1.11制作了一个小型Rest Web服务。 当我调用返回Json的url时,非英语字符的字符编码存在问题。 Xml的相应URL(“ test.xml”在开始的xml-tag中使其成为utf-8。

如何使网址“ test.json”返回utf-8编码的响应?

这是该服务的代码:

@Stateless

@Path("/")

public class RestTest {

@EJB

private MyDao myDao;

@Path("test.xml/")

@GET

@Produces(MediaType.APPLICATION_XML )

public List getProfiles() {

return myDao.getProfilesForWeb();

}

@Path("test.json/")

@GET

@Produces(MediaType.APPLICATION_JSON)

public List getProfilesAsJson() {

return myDao.getProfilesForWeb();

}

}

这是服务使用的pojo:

package se.kc.mimee.profile.model;

@XmlRootElement

public class Profile {

public int id;

public String name;

public Profile(int id, String name) {

this.id = id;

this.name = name;

}

public Profile() {}

}

7个解决方案

96 votes

Jersey在默认情况下应始终生成utf-8,听起来像是您的客户端无法正确解释它(xml声明不会“使其”成为utf-8,只是告诉客户端如何解析它)。

您看到哪个客户遇到这些问题?

有效JSON仅应为Unicode(utf-8 / 16/32); 解析器应该能够自动检测编码(当然有些解析器不能),因此JSON中没有编码声明。

您可以像这样将其添加到Content-Type中:

@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")

Dmitri answered 2020-07-09T23:11:04Z

5 votes

如果不是将字符集添加到每个资源中,那么此问题的答案(表明如何实施默认字符集)也许会有所帮助。

martin answered 2020-07-09T23:11:24Z

3 votes

responseMessage是Bean类,我们可以在其中发送UTF-8 charset作为响应。

return Response.ok(responseMessage).header("Content-Type", "application/json;charset=UTF-8").build();

Prem Kumar answered 2020-07-09T23:11:44Z

3 votes

如果@Produces(MediaType.APPLICATION_JSON +“; charset = utf-8”)不起作用,请尝试:

@Produces(“ application / json; charset = utf-8”)

理论上是一样的,但是第一种选择对我没有用

alexcornejo answered 2020-07-09T23:12:13Z

0 votes

您也可以尝试以下方法:

return Response.ok(responseMessage, "application/json;charset=UTF-8").build();

K.Alianne answered 2020-07-09T23:12:32Z

0 votes

泽西(Jersey)有问题,当使用Content-Type application / json时,它不会像预期的那样自动检测unicode JSON编码,而是使用服务器使用的任何运行时平台编码对请求主体进行反序列化。 响应主体序列化也是如此。

您的客户需要明确指定UTF-8字符集:

Content-Type: application/json;charset=utf-8

Dušan Zahoranský answered 2020-07-09T23:12:57Z

-1 votes

我在servlet中遇到了同样的问题

请使用:resp.setContentType(“ application / json; charset = utf-8”);

public static void flashOutput(HttpServletRequest req

, HttpServletResponse resp

, String output) {

try {

Utils.print2("output flash"+output);

resp.setContentType("application/json;charset=utf-8");

PrintWriter pw = resp.getWriter();

pw.write( new String(output.getBytes("UTF-8")));

pw.close();

resp.flushBuffer();

} catch (Exception e) {

// TODO: handle exception

}

}// end flashOutput

Vinod Joshi answered 2020-07-09T23:13:21Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值