Springboot中JsonView的使用求教
燃木刀法 2018-12-03 04:35:50 问题描述:在使用JsonView定制接口响应结果的过程中,如果返回的结果是自带的数据类型定制没有问题、如果自己封装的数据类型结果返回为空。请各位大大们指点迷津,感激不尽。
具体代码如下:
1. DataUtil.java类
public class DataUtil {
public static List<Book> getData() {
List<Book> result = new ArrayList();
Book book = new Book(), book1 = new Book();
book.setName("Java 编程思想");
book.setCreate(new Date());
book.setPrice(100);
book.setTitle("N-2018.08.09");
result.add(book);
book1.setName("Thinking Java");
book1.setCreate(new Date());
book1.setPrice(130);
book1.setTitle("N-2018.10.06");
result.add(book1);
return result;
}
}
2. Book.java类
public class Book {
public interface BookSimple {
}
public interface BookDetail extends BookSimple {
}
@JsonView(BookSimple.class)
private String name;
@JsonView(BookSimple.class)
private String title;
@JsonView(BookDetail.class)
private int price;
@JsonView(BookDetail.class)
private Date create;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Date getCreate() {
return create;
}
public void setCreate(Date create) {
this.create = create;
}
}
3. MyResult.java
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyResult implements Serializable {
private int code;
private String message;
private Object result;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
4. JsonController.java
下面的这种形式返回数据是空的:
@RestController
@RequestMapping("/json")
public class JsonController {
@GetMapping("/list")
@JsonView(Book.BookDetail.class)
public Object list(MyResult myResult) {
List<Book> all = DataUtil.getData();
myResult.setResult(all);
return myResult;
}
}
修改成这样,直接返回List就可以实现JsonView的功能
@RestController
@RequestMapping("/json")
public class JsonController {
@GetMapping("/list")
@JsonView(Book.BookDetail.class)
public Object list(MyResult myResult) {
List<Book> all = DataUtil.getData();
myResult.setResult(all);
return all;
}
}
拜托了,各位。