1 回答
TA贡献1820条经验 获得超2个赞
是的,您可以使用Jackson @JsonView来做到这一点。
首先,您必须创建一个类来声明您的观点。
public class PersonResponseViews {
public static class Person { }
public static class Profile { }
}
PersonResponse那么你必须在类中包含这些更改
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
class PersonResponse {
@JsonView(PersonResponseViews.Person.class)
String name;
@JsonView(PersonResponseViews.Person.class)
Profile profile;
@JsonView({
PersonResponseViews.Person.class,
PersonResponseViews.Profile.class
})
Error error;
@JsonProperty("id")
@JsonView(PersonResponseViews.Profile.class)
int getProfileId() {
int id = 0;
if (profile != null) {
id = profile.id;
}
return id;
}
@JsonView({
PersonResponseViews.Person.class,
PersonResponseViews.Profile.class
})
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
static class Error {
String message;
int code;
}
@JsonView(PersonResponseViews.Person.class)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
static class Profile {
int id;
}
}
如何将JSON视图与Spring Rest 控制器一起使用
@JsonView(PersonResponseViews.Person.class)
@RequestMapping("/person")
public @ResponseBody
PersonResponse getPerson() {
PersonResponse resp = new PersonResponse();
resp.name = "first last";
resp.profile = new PersonResponse.Profile();
resp.profile.id = 1234;
resp.error = new PersonResponse.Error();
resp.error.code = 404;
resp.error.message = "some random error";
return resp;
}
@JsonView(PersonResponseViews.Profile.class)
@RequestMapping("/profile")
public @ResponseBody
PersonResponse getProfile() {
PersonResponse resp = new PersonResponse();
resp.profile = new PersonResponse.Profile();
resp.profile.id = 1234;
resp.error = new PersonResponse.Error();
resp.error.code = 404;
resp.error.message = "some random error";
return resp;
}
添加回答
举报