我已经设置了这个简单的Java类:
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;
}
}
现在使用JAX-RS我正在实现并将此类作为JSON返回,就像这样;
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 Person getList() {
Person p1 = new Person();
p1.setName("táòt");
p1.setId(1);
p1.setGender("M");
return p1;
}
}
我的servlet初始化类是这样的:
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;
}
}
我得到的结果就像JSON一样:
{"person":{"name":"t\u00e1\u00f2t","gender":"M","id":"1"}}
正如您所看到的那样,JSON字符串是Java编码的,我正在解释为什么会发生这种情况,我该怎样才能克服这个...
帮助将不胜感激......
答案 0 :(得分:2)
信不信由你,结果很好。它不是Java编码的,它只是将非ASCII字符作为unicode代码点(\ u ...)返回。将它加载到像JSON那样的Javascript中,你会注意到它打印并解码它:
>>> p={"person":{"name":"t\u00e1\u00f2t","gender":"M","id":"1"}}
>>> p.person.name
"táòt"