gpt4 book ai didi

java - 使用 RESTful Jersey 返回自定义 JSON

转载 作者:行者123 更新时间:2023-12-02 05:50:22 25 4
gpt4 key购买 nike

这是我第一次尝试 Maven 和 Jersey。我读过很多关于 JSON 的文章。我想知道我的问题是否可以在没有 JSON simple 和 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;

最佳答案

如果你想要这种形式的 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 这样的库,这与 Jersey 配合得很好。你只需要在你的类路径中使用 Genson,然后它就会自动启用并处理 json ser/de。

关于java - 使用 RESTful Jersey 返回自定义 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com