Nak*_*ule 3 java rest spring-boot
假设有以下类:
public class Foo {
String a, b, c, d;
// The rest of the class...
}
Run Code Online (Sandbox Code Playgroud)
还有一个使用 Springboot 的 REST API 控制器:
@GetMapping("/foo")
public Foo myFuntion() {
return new Foo(...);
}
Run Code Online (Sandbox Code Playgroud)
请求/foo返回此 JSON:
{
"a": "...",
"b": "...",
"c": "...",
"d": "..."
}
Run Code Online (Sandbox Code Playgroud)
但是,我只想返回Foo类的某些属性,例如,仅返回属性a和b.
如果不创建新类,我怎么能做到这一点?
你有两个解决方案
在要排除的属性上使用 @JsonIgnore
例如,您想从序列化中排除a。(只想得到b,c,d)
public class TestDto {
@JsonIgnore
String a;
String b;
String c;
String d;
//Getter and Setter
}
Run Code Online (Sandbox Code Playgroud)
使用 @JsonInclude 和 @JsonIgnoreProperties
通过此解决方案,如果 a、b、c、d 中的每一个都为空,则它将从响应中排除。
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class TestDto {
String a;
String b;
String c;
String d;
//getters and setter
}
Run Code Online (Sandbox Code Playgroud)