如何返回Jersey / Jackson的JSON对象列表

时间:2017-02-07 03:21:08

标签: json list jersey jackson

我使用Jersey / Jackson作为JSON的返回对象。 我可以为单个对象成功返回它,但我无法返回列表。

如何将列表对象序列化返回到JSON

这是我的例子

像这样的依赖:

 <dependencies>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-bundle</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-core</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.19</version>
    </dependency>


</dependencies>

我的模特喜欢这个:

public class Person {


private String name;
private String surname;
private int age;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getSurname() {
    return surname;
}
public void setSurname(String surname) {
    this.surname = surname;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public Person(String name, String surname, int age) {
    super();
    this.name = name;
    this.surname = surname;
    this.age = age;
}
public Person() {
    super();
}


@Override
public String toString() {


    return "Person [name="+ name +", surname="+ surname +", age="+ age +"]";
}

我的服务是这样的:

@Path("/getperson")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Person getPerson(){

    Person person = new Person(name, surname, age);



    return person;

}


@Path("/getpersons")
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Person> getPersons(){

    Person p1 = new Person("gosling", "james", 55);
    Person p2 = new Person("torvalds", "linus", 48);
    Person p3 = new Person("riche", "dennis", 60);

    List<Person> persons = new ArrayList<Person>();
    persons.add(p1);
    persons.add(p2);
    persons.add(p3);

    return persons;


}

getPerson()运行良好,但getpersons()返回空。

1 个答案:

答案 0 :(得分:0)

在我的场景中,我使用的是glassfish jersey依赖项:

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
    </dependency>

并且几乎按照我想要的0配置或映射返回列表。 我的代码中没有任何特定问题。