Joj*_*jje 45 java jersey character-encoding
我使用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<Profile> getProfiles() {
return myDao.getProfilesForWeb();
}
@Path("test.json/")
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Profile> getProfilesAsJson() {
return myDao.getProfilesForWeb();
}
}
Run Code Online (Sandbox Code Playgroud)
这是服务使用的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() {}
}
Run Code Online (Sandbox Code Playgroud)
Dmi*_*tri 97
泽西岛应该总是默认生成utf-8,听起来问题是你的客户端没有正确解释它(xml声明没有"make"它utf-8,只是告诉客户端如何解析它).
你看到这些问题的客户是什么?
有效的JSON应该只是Unicode(utf-8/16/32); 解析器应该能够自动检测编码(当然,有些则不然),因此JSON中没有编码声明.
您可以将它添加到Content-Type类似的内容中:
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
Run Code Online (Sandbox Code Playgroud)
如果@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") 不起作用,请尝试:
@Produces("application/json;charset=utf-8")
理论上是一样的,但第一个选项对我不起作用
小智 5
responseMessage是 bean 类,我们可以在其中发送UTF-8 charset响应。
return Response.ok(responseMessage).header("Content-Type", "application/json;charset=UTF-8").build();
Run Code Online (Sandbox Code Playgroud)