我正在使用Jersey来使我的一些服务RESTful.
我的REST服务调用返回给我
{"param1":"value1","param2":"value2",...."paramN":"valueN"}
但是,我希望它能够回归
["param1":"value1",...."paramN":"valueN"]
我需要在下面的代码中做出哪些更改?
@GET @Produces(MediaType.APPLICATION_JSON) public List<com.abc.def.rest.model.SimplePojo> getSomeList() { /* Do something */ return listOfPojos; }
我的web.xml文件的一部分看起来像这样
<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>
谢谢!
您可以使用Person POJO定义您的服务方法,如下所示:
原文链接:https://www.f2er.com/json/288470.html@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(); }
POJO课程:
@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; } } }
结果如下:
[{"fn":"1","ln":"2"},{"fn":"3","ln":"4"},{"fn":"5","ln":"6"}]