1 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超2個(gè)贊
是的,您可以使用Jackson @JsonView來(lái)做到這一點(diǎn)。
首先,您必須創(chuàng)建一個(gè)類來(lái)聲明您的觀點(diǎn)。
? ? 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;
? ? }
添加回答
舉報(bào)