Java 将两个不同的JSON表示反序列化为一个对象

Java 将两个不同的JSON表示反序列化为一个对象,java,spring,jackson,lombok,Java,Spring,Jackson,Lombok,我有类似Java的类 @数据 公开课评论{ 私有整数id;//无论如何都应使用 private Long refId;//用于内部目的->不序列化 私有字符串text;//应在QuickComment中使用 私有字符串patch;//仅应包含在PatchComment中 私有字符串状态;//仅应包含在StatusComment中 } 我有 @数据 公众课堂反应{ 私人评论; 私人评论; } 我考虑过像这样使用JsonView 公共类视图{ 公共接口状态注释{} 公共接口补丁注释{} } 并

我有类似Java的类

@数据
公开课评论{
私有整数id;//无论如何都应使用
private Long refId;//用于内部目的->不序列化
私有字符串text;//应在QuickComment中使用
私有字符串patch;//仅应包含在PatchComment中
私有字符串状态;//仅应包含在StatusComment中
}
我有

@数据
公众课堂反应{
私人评论;
私人评论;
}
我考虑过像这样使用
JsonView

公共类视图{
公共接口状态注释{}
公共接口补丁注释{}
}
并将它们应用于inital类

@数据
公开课评论{
@JsonView({Views.StatusComment.class,Views.PatchComment.class})
私有整数id;//无论如何都应使用
private Long refId;//用于内部目的->不序列化
@JsonView({Views.StatusComment.class,Views.PatchComment.class})
私有字符串text;//无论如何都应该使用
@JsonView(Views.PatchComment.class)
私有字符串patch;//仅应包含在PatchComment中
@JsonView(Views.StatusComment.class)
私有字符串状态;//仅应包含在StatusComment中
}
以及
响应

@数据
公众课堂反应{
@JsonView(Views.StatusComment.class)
私人评论;
@JsonView(Views.PatchComment.class)
私人评论;
}

但不知何故,它完全失败了。它完全失败了。龙目山有问题吗。还是定义不正确?

如何序列化对象?你在用弹簧吗?您是否直接使用
ObjectMapper

如果您使用的是Spring,则需要使用
@JsonView(Views.StatusComment.class)
@JsonView(Views.PatchComment.class)
注释控制器的方法,如:

用于读取
GET
端点

@JsonView(Views.StatusComment.class)
@请求映射(“/comments/{id}”)
公共注释getStatusComments(@PathVariable int-id){
return statusService.getStatuscommentById(id);
}
写作:

@RequestMapping(value=“/persons”,consumes=APPLICATION\u JSON\u value,method=RequestMethod.POST)
公共注释saveStatusComment(@JsonView(View.StatusComment.class)@RequestBody注释c){
返回statusService.saveStatusComment(c);
}
如果直接使用
对象映射器
,则需要指定使用的
视图

写作时:

ObjectMapper mapper=new ObjectMapper();
字符串结果=映射器
.writerWithView(Views.StatusComment.class)
.writeValueAsString(注释);
阅读时:

ObjectMapper mapper = new ObjectMapper();
Comment comment = mapper
    .readerWithView(Views.StatusComment.class)
    .forType(Comment.class)
    .readValue(json);

啊。。。但是这意味着我没有得到一个同时包含两个条目的对象?e、 g.
返回响应
。条目的内容不同。使用
视图
可以在不同的上下文中使用相同的对象。例如,您有一个对象的公共版本和一个只供您自己使用的版本。然后,您可以只使用一个类,但根据使用的视图,您将看到不同的内容。啊。。。。我懂了。。。如何为同一对象获取两个不同版本的内容?(使用Spring)我添加了一个示例