[英]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.