开发者

JAX-RS and JSON messed up

I've Set up this simple Java Class:

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
    private int id;
    private String name;
    private String gender;      

    public Person() {       
    }

    public void setId(int id) {
             this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getGender() {
        return this.gender;
    }           
}

Now using JAX-RS I'm instatiating and returning this Class as JSON like so;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path(value="/addresses")
public class AddressBook extends Person {   

    public AddressBook() {

    }    

    @GET    
    @Produces("application/json;charset=iso-8891-1")    
    public Perso开发者_如何学Cn getList() { 

        Person p1 = new Person();
        p1.setName("táòt");
        p1.setId(1);
        p1.setGender("M");

        return p1;
    }

}

My servlet initialization class is like this:

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;

public class AddressBookApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(AddressBook.class);
        return classes;
    }
}

The result I'm getting as JSON is this:

{"person":{"name":"t\u00e1\u00f2t","gender":"M","id":"1"}}

As you can see the JSON string is Java encoded and I'm pulling my hair out with why this is happening and how can I overcome this...

Help would be appreciated...


Believe it or not, your result is fine. It's not Java encoded, it's just returning the non-ASCII characters as unicode codepoints (the \u...). Load this into Javascript like JSON is supposed to, and you'll notice it prints and decodes it:

    >>> p={"person":{"name":"t\u00e1\u00f2t","gender":"M","id":"1"}}
    >>> p.person.name
    "táòt"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜