Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

jax rs - Return JSONArray instead of JSONObject, Jersey JAX-RS

I am using Jersey to make some of my services RESTful.

My REST service call returns me

{"param1":"value1", "param2":"value2",...."paramN":"valueN"}

But, I want it to return

["param1":"value1", "param2":"value2",...."paramN":"valueN"]

What are the changes I need to make in the code below?

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<com.abc.def.rest.model.SimplePojo> getSomeList() {
    /* 
            Do something
    */
    return listOfPojos;
}

Part of my web.xml file looks like this

    <servlet>
        <servlet-name>Abc Jersey REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.abc.def.rest</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can define your service method as follows, using Person POJO:

@GET
@Produces("application/json")
@Path("/list")
public String getList(){
    List<Person> persons = new ArrayList<>();
    persons.add(new Person("1", "2"));
    persons.add(new Person("3", "4"));
    persons.add(new Person("5", "6"));
    // takes advantage to toString() implementation to format as [a, b, c]
    return persons.toString();
}

The POJO class:

@XmlRootElement
public class Person {
    @XmlElement(name="fn")
    String fn;

    @XmlElement(name="ln")
    String ln;

    public Person(){        
    }

    public Person(String fn, String ln) {
        this.fn = fn;
        this.ln = ln;
    }    

    @Override
    public String toString(){
        try {
            // takes advantage of toString() implementation to format {"a":"b"}
            return new JSONObject().put("fn", fn).put("ln", ln).toString();
        } catch (JSONException e) {
            return null;
        }
    }
}

The results will look like:

[{"fn":"1","ln":"2"}, {"fn":"3","ln":"4"}, {"fn":"5","ln":"6"}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...