JAX-RS打印Object []列表为json / xml

时间:2017-04-11 07:13:27

标签: java jax-rs

我知道jax-rs

你能帮我知道如何打印jax-rs

List<Object[]>

拜托,谢谢。

2 个答案:

答案 0 :(得分:1)

你可以看到这个(Does rest supports arraylist of objects?

对于jax-rs,你可以使用Jersey

首先你应该创建:

@XmlRootElement(name = "responseList")
public class ResponseList {

    private List<Object> list;
    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }

}

我们可以使用String作为对象(或任何其他对象):

  @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_XML)
    public ResponseList addObjects() {

        String string1 = "s1"; 
        String string2 = "s2";

        ArrayList<Object> list = new ArrayList<Object>();
        list.add(string1);
        list.add(string2);
        ResponseList strings=new ResponseList();
        strings.setList(list);

        return strings;   
    }

pom.xml:

<dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>2.12</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>2.12</version>
        </dependency>

结果是:

<responseList>
    <list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">s1</list>
    <list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">s2</list>
    </responseList>

答案 1 :(得分:1)

您可以使用'杰克逊图书馆'

ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(...your list object...);