java - 将两种不同的 JSON 表示反序列化为一个对象
问题描述
我有 Java 类
@Data
public class Comment {
private Integer id; // should be used anyhow
private Long refId; // for internal purpose -> not be serialized
private String text; // should be used in QuickComment
private String patch; // should be included in PatchComment ONLY
private String status; // should be included in StatusComment ONLY
}
我有
@Data
public class Response{
private Comment statusComment;
private Comment patchComment;
}
我想过使用JsonView
like
public class Views{
public interface StatusComment{}
public interface PatchComment{}
}
并将它们应用于初始类
@Data
public class Comment {
@JsonView({Views.StatusComment.class, Views.PatchComment.class})
private Integer id; // should be used anyhow
private Long refId; // for internal purpose -> not be serialized
@JsonView({Views.StatusComment.class, Views.PatchComment.class})
private String text; // should be used anyhow
@JsonView(Views.PatchComment.class)
private String patch; // should be included in PatchComment ONLY
@JsonView(Views.StatusComment.class)
private String status; // should be included in StatusComment ONLY
}
和Response
@Data
public class Response{
@JsonView(Views.StatusComment.class)
private Comment statusComment;
@JsonView(Views.PatchComment.class)
private Comment patchComment;
}
但不知何故,它完全失败了。它完全失败了,即。什么都没有过滤。龙目岛有问题吗?还是定义不正确?
解决方案
你如何序列化你的对象?你用的是弹簧吗?你是ObjectMapper
直接用的吗?
如果您使用的是 Spring,那么您需要做的是使用@JsonView(Views.StatusComment.class)
或@JsonView(Views.PatchComment.class)
类似注释控制器的方法:
用于读取GET
端点
@JsonView(Views.StatusComment.class)
@RequestMapping("/comments/{id}")
public Comment getStatusComments(@PathVariable int id) {
return statusService.getStatuscommentById(id);
}
对于写作:
@RequestMapping(value = "/persons", consumes = APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public Comment saveStatusComment(@JsonView(View.StatusComment.class) @RequestBody Comment c) {
return statusService.saveStatusComment(c);
}
如果您ObjectMapper
直接使用,那么您需要做的是指定 used View
:
写作时:
ObjectMapper mapper = new ObjectMapper();
String result = mapper
.writerWithView(Views.StatusComment.class)
.writeValueAsString(comment);
阅读时:
ObjectMapper mapper = new ObjectMapper();
Comment comment = mapper
.readerWithView(Views.StatusComment.class)
.forType(Comment.class)
.readValue(json);
推荐阅读
- vba - 运行时错误“-2147417848 (80010108)”:对象“_Worksheet”的方法“单元格”失败
- servicestack - 如何测试用户是否在 ServiceStack 中的服务实现中具有角色
- java - 获取 java.lang.IllegalStateException:未找到线程绑定请求
- python - 第 1 行带有打印语句的错误令牌
- cakephp - 如何在 CakePHP3 中正确使用 group by
- c# - Azure 服务的 .Net Core 异步方法
- google-maps - 在谷歌地图上显示用户位置
- scala - 如何使用延迟初始化对元组进行模式匹配?
- powershell - Powershell、RunAs 与凭据
- excel - 添加第三个条件来自动过滤 VBA