Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I made a small Rest webservice using Jersey 1.11. When i call the url that returns Json, there are problems with the character encoding for non english characters. The corresponding url for Xml ("test.xml" makes it utf-8 in the starting xml-tag.

How can I make the url "test.json" return utf-8 encoded response?

Here's the code for the service:

@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();
    }
}

This is the pojo that the service uses:

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() {}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
501 views
Welcome To Ask or Share your Answers For Others

1 Answer

Jersey should always produce utf-8 by default, sounds like the problem is that your client isn't interpreting it correctly (the xml declaration doesn't "make" it utf-8, just tells the client how to parse it).

What client are you seeing these problems with?

Valid JSON is only supposed to be Unicode (utf-8/16/32); parsers should be able to detect the encoding automatically (of course, some don't), so there is no encoding declaration in JSON.

You can add it to the Content-Type like so:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...