内部对象的JSON到Java映射?
我有以下课程:内部对象的JSON到Java映射?,java,json,spring-boot,jackson,Java,Json,Spring Boot,Jackson,我有以下课程: public class PersonResponse { public static final class Profile { int id; } public static class Error { String message; int code; } String name; Profile profile; //getters/setters } 要映射JSON
public class PersonResponse {
public static final class Profile {
int id;
}
public static class Error {
String message;
int code;
}
String name;
Profile profile;
//getters/setters
}
要映射JSON响应,请执行以下操作:
{
"name" : "first last",
"profile" : {
"id" : 1234
},
"error" : {
"message": "some random error",
"code" : 404
}
}
这很好,但我有一个端点只返回Profile
对象或一些错误。因此,答复可以是:
{
"id" : 1234
}
或
在这种情况下,有没有办法重用
PersonResponse
类,而不是在Profile
对象中添加一个错误对象?是的,您可以使用Jackson@JsonView
来完成
首先,必须创建一个用于声明视图的类
公共类PersonResponseViews{
公共静态类Person{}
公共静态类配置文件{}
}
然后您必须将这些更改包括在PersonResponse
类中
import com.fasterxml.jackson.annotation.jsonautodect;
导入com.fasterxml.jackson.annotation.JsonProperty;
导入com.fasterxml.jackson.annotation.JsonView;
@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY)
类人反应{
@JsonView(PersonResponseViews.Person.class)
字符串名;
@JsonView(PersonResponseViews.Person.class)
剖面图;
@JsonView({
PersonResponseViews.Person.class,
PersonResponseViews.Profile.class
})
误差;
@JsonProperty(“id”)
@JsonView(PersonResponseViews.Profile.class)
int getProfileId(){
int id=0;
if(profile!=null){
id=profile.id;
}
返回id;
}
@JsonView({
PersonResponseViews.Person.class,
PersonResponseViews.Profile.class
})
@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY)
静态类错误{
字符串消息;
int代码;
}
@JsonView(PersonResponseViews.Person.class)
@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY)
静态类配置文件{
int-id;
}
}
如何将JSON视图与Spring Rest控制器一起使用
@JsonView(PersonResponseViews.Person.class)
@请求映射(“/人”)
公共@ResponseBody
PersonResponse getPerson(){
PersonResponse resp=新的PersonResponse();
resp.name=“first-last”;
resp.profile=新的PersonResponse.profile();
resp.profile.id=1234;
resp.error=newpersonresponse.error();
resp.error.code=404;
resp.error.message=“一些随机错误”;
返回响应;
}
@JsonView(PersonResponseViews.Profile.class)
@请求映射(“/profile”)
公共@ResponseBody
PersonResponse getProfile(){
PersonResponse resp=新的PersonResponse();
resp.profile=新的PersonResponse.profile();
resp.profile.id=1234;
resp.error=newpersonresponse.error();
resp.error.code=404;
resp.error.message=“一些随机错误”;
返回响应;
}
您使用的是Spring Boot吗?@EduardoEljaiek yesI正在发布一个使用@JSONVIEWS的解决方案。如果这对您有用,请记住它,也许还可以。
{
"message": "profile not found",
"code" : 404
}