簡體   English   中英

Jackson和多接口繼承

[英]Jackson and multiple interface inheritance

我正在嘗試根據使用的接口將單個實體的json序列化為不同的視圖。 例如,我們有:

public interface BookBrief {
  long getId();
  String getTitle();
}

public interface BookPreview {
  long getId();
  String getAnnotation();
}

public class Book implements BookBrief, BookPreview {

  // class fields here

  public long getId() {...}

  public String getTitle() {...}

  public String getText() {...}

  public String getAnnotation() {...}

  // setters here
}


// service which results is serialized to json in Spring MVC controllers

public interface BookService {

  List<? extends BookBrief> getBooks();

  BookPreview getBookPreview(long id);

  Book getBook(long id);
}

BookService實現始終返回Book類(未使用的字段設置為null)。 為了序列化接口,我嘗試為每個接口使用注解@JsonSerialize(as = Interface.class),但是對於所有接口,傑克遜始終僅使用“實現”表達式中列出的第一個接口。 有沒有一種方法可以像我一樣配置傑克遜? 還是有更好的解決方案?

似乎您有2個選擇:

  1. 編寫自定義的Jackson序列化器
  2. 使用Jackson視圖,看起來更可行(可以在此處找到完整的文檔)。

使用Views可以通過3個簡單的步驟來實現:

  1. 定義您的視圖標記:

BookViews.java

public class BookViews {

    public static class BookBrief { }

    public static class BookPreview { }

}
  1. 注釋要在每個視圖中公開的“圖書”字段:

Book.java

public class Book {

    @JsonView({BookViews.BookBrief.class, BookViews.BookPreview.class})
    private long id;

    @JsonView(BookViews.BookBrief.class)
    private String title;

    @JsonView(BookViews.BookPreview.class)
    private String annotation;

    // Constructors and getters/setters
}
  1. 用JSonValue注釋REST方法,並指定要使用的視圖:

BookService.java

@Path("books")
public class BookService {

    private static final List<Book> library = Arrays.asList(
            new Book(1, "War and Peace", "Novel"),
            new Book(2, "A Game of Thrones", "Fantasy")
    );

    @GET
    @Path("all")
    @JsonView(BookViews.BookBrief.class)
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBooks() {
        return Response.status(Response.Status.OK).entity(library).build();
    }

    @GET
    @Path("previews")
    @JsonView(BookViews.BookPreview.class)
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBookPreviews() {
        return Response.status(Response.Status.OK).entity(library).build();
    }

}

結果

GET http:// localhost:8080 / root / rest / books / all

[
    {
        "id": 1,
        "title": "War and Peace"
    },
    {
        "id": 2,
        "title": "A Game of Thrones"
    }
]

GET http:// localhost:8080 / root / rest / books / previews

[
    {
        "annotation": "Novel",
        "id": 1
    },
    {
        "annotation": "Fantasy",
        "id": 2
    }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM