[英]Returning custom JSON with RESTful Jersey
这是我第一次尝试使用Maven和Jersey。 我已经阅读了很多关于JSON的文章。 我想知道如果没有简单的JSON和GSON,我的问题是否可以解决。
当我访问localhost:8080/helloWorld/example1/example2/example3
,我得到这样的东西
{"first": example1, "second": example2, "third":example3}
这对一开始很好,但我希望得到这样的回复:
{
"firstMap": {"first": example1, "second": example2},
"secondMap":{"third": example3}
}
我试图创建responseWrapper类,但它返回
{
"firstMap": {"first": example1, "second": example2, "third": null},
"secondMap":{"first": null, "second": null, "third": example3}
}.
我不希望显示这些空值。 我该怎么做?
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("sample")
public class HelloWorldService {
@Path("/helloWorld/{first}/{second}/{third}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public HelloWorld helloWorld(@PathParam("first") String first, @PathParam("second") String second, @PathParam("third") String third) {
return new HelloWorld(first, second, third);
}
}
并且:
public class HelloWorld {
private String first;
private String second;
private String third;
public HelloWorld(String first, String second) {
this.first = first;
this.second = second;
}
public HelloWorld(String third, String third) {
this.third = third;
}
public HelloWorld(){
}
public HelloWorld(String first) {
this.first= first;
}
public String getFirst() {
return first;
}
public String getSecond(){
return second;
}
public String getThird(){
return third;
如果您只是为了这种用法而需要它,您可以尝试模仿类本身,以便在序列化时它将以您想要的格式生成。 Gson将允许您为类编写自定义序列化和反序列化,但随后您将失去自动化。 这可能是HelloWorld
类的代码:
public class HelloWorld {
public class Data1
{
private String first;
private String second;
// getter and setters...
}
private Data1 firstMap;
public class Data2
{
private String third;
// getter and setters...
}
private Data2 secondMap;
// ...
}
如果你想要一个这种形式的json
{
"firstMap": {"first": example1, "second": example2},
"secondMap":{"third": example3}
}
从服务返回的对象应具有此结构。
public class Root {
public First firstMap;
public Third secondMap;
}
public class First {
public String first;
public String second;
}
public class Third {
public String third;
}
然后你可以使用像Genson这样的图书馆,与泽西岛很好地搭配。 您只需在类路径中使用Genson,然后它将自动启用并处理json ser / de。
Gson有一个GsonBuilder类来在构造Gson主对象时设置格式化标志。 查找setPettyPrinting()
以在人类可读和serializeNulls()
格式化它以切换打印null。 默认情况下,打印空值关闭。 从Web服务中使用它时,Jackson库可以为您提供更多的注释控制,并且可以更好地与spring集成。 如果您使用Spring,我强烈推荐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.