我有2个课程-2个实体-Book和BookRentals。 BookRentals将Book对象放入其中。
我想忽略BookRentals中Book的属性之一。这是available
属性。
我有负责找到所有租金的方法。 JSON中的输出如下所示:
[
{
"id": 1,
"book": {
"id": 1,
"title": "Krzyżacy",
"author": "Henryk Sienkiewicz",
"category": "powieść historyczna",
"available": false
},
"user": {
"id": 2,
"name": "piotri",
"password": "123"
}
}
]
如您所见,这里不是必需的,但是我不能在Book类中设置
@JsonIgnore
,因为查找所有书籍都需要此变量:[
{
"id": 1,
"title": "Krzyżacy",
"author": "Henryk Sienkiewicz",
"category": "powieść historyczna",
"available": false
}
]
书本类:
package bookrental.model.book;
import lombok.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@NotNull
private String title;
@NotNull
private String author;
@NotNull
private String category;
private boolean available;
public Book(String title, String author, String category, boolean available) {
this.title = title;
this.author = author;
this.category = category;
this.available = available;
}
}
BookRentals类
package bookrental.model.book;
import bookrental.model.account.User;
import lombok.*;
import javax.persistence.*;
@Entity
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
public class BookRentals {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToOne
private Book book;
@OneToOne
private User user;
public BookRentals(Book book, User user) {
this.book = book;
this.user = user;
}
}
我应该怎么做?
最佳答案
您可以使用ResponseEntity和JsonSerializer(包括和排除)jackson进行相同的操作。
return new JSONSerializer().transform(new DateTransformer("MM/dd/yyyy HH:mm:ss"), java.util.Date.class).include("field1").exclude("field2").serialize(pojoObject);
然后从控制器返回如下响应。
return new ResponseEntity<String>(new JSONSerializer().transform(new DateTransformer("MM/dd/yyyy HH:mm:ss"), java.util.Date.class).include("field1").exclude("field2").serialize(pojoObject), headers,HttpStatus.OK);
您的控制器方法如下所示。
@RequestMapping(value = "/getUser", method = RequestMethod.GET,produces="application/json")
@ResponseBody
public ResponseEntity<String> getUser(@RequestParam(value = "userId", required = true) String userId)
{
User user = userService.findByUserId(userId);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
return new ResponseEntity<String>(new JSONSerializer().transform(new DateTransformer("MM/dd/yyyy HH:mm:ss"), java.util.Date.class).include("field1").exclude("field2").serialize(user), headers,HttpStatus.OK);
}