我是Jersey REST的新手,我正在尝试构建一个示例库系统。我创建了BookResource.java,我希望它在浏览器中显示以下输出:
{
“book” : {
“isbn” : 1,
“title” : “Programming Amazon EC2”,
“publication-date” : “2/11/2011”,
“language” : “eng”,
“num-pages”: 185,
“status” : “available”,
“authors” : [
{ “rel”: “view-author”, “href”: “/books/1/authors/1”, “method”: “GET” },
{ “rel”: “view-author”, “href”: “/books/1/authors/2”, “method”: “GET” }
]
},
"links" : []
}
My Book.java如下:
public class Book
{
private long isbn;
private String title;
@JsonProperty("publication-date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy")
private String date;
private String language;
private String status;
@JsonProperty("num-pages")
private Integer num_pages;
@JsonProperty("authors")
private ArrayList<Author> authorList;
public Book() {}
//getters and setters
}
Author.java
public class Author
{
@JsonProperty("name")
private String name;
public Author() {}
public String getAuthor() {
return name;
}
public void setAuthor(String newAuthor){
this.name = newAuthor;
}
}
BookRepository.java
public class BookRepository implements BookRepositoryInterface {
public ArrayList<Author> getAuthorByIsbn(Long isbn)
{
Book newBook = bookInMemoryMap.get(isbn);
ArrayList<Author> authorList = newBook.getAuthor();
return authorList;
}
}
但是我在浏览器上的实际GET响应显示为:
{
"book": {
"isbn": 1,
"title": "Programming EC2r",
"language": "eng",
"status": "available",
"author": [{
"name": "auth1",
"author": "auth1"
}, {
"name": "auth2",
"author": "auth2"
}],
"num_Pages": 185,
"publication-date": "2/11/2011",
"num-pages": 185,
"authors": [{
"name": "auth1",
"author": "auth1"
}, {
"name": "auth2",
"author": "auth2"
}]
}
BookResource.java
public class BookResource
{
@GET
@Path("/{isbn}")
@Timed(name = "view-book")
public BookDto getBookByIsbn(@PathParam("isbn") LongParam isbn)
{
Book book = bookRepository.getBookByISBN(isbn.get());
BookDto bookResponse = new BookDto(book);
// add more links
bookResponse.addLink(new LinkDto("view-book", "/books/" + book.getIsbn(),"GET"));
return bookResponse;
}
}
我为author和num_pages获取了多个值,似乎无法正确显示输出。 我试过@JsonPropertyOrder,但它没有用。 此外,在调试中我检查了Book资源是否正确存储和检索。它只是显示多个值的JSON输出。我怎么能纠正这个? 另外,如何根据需要显示“作者”的链接?
答案 0 :(得分:0)
感谢@SvetlinZarev,通过将 @JsonProperty仅放在getter方法上,我能够解决显示多个值的问题。
@JsonProperty("name")
public String getAuthor() {
return name;
}
它工作得很好,它显示我的正确输出如下:
{
"book": {
"isbn": 1,
"title": "Programming EC2r",
"publication-date": "2/11/2011",
"language": "eng",
"num-pages": 185,
"status": "available",
"authors": [{
"name": "auth1"
}, {
"name": "auth2"
}]
},
"links": []
}
再次感谢大家对我这样的新手的及时回复! :)