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

标签 java spring jackson lombok

我有像这样的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

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
}

响应

@Data
public class Response{
  @JsonView(Views.StatusComment.class)
  private Comment statusComment;
  @JsonView(Views.PatchComment.class)
  private Comment patchComment;
}

但不知怎的,它完全失败了。它完全失败了,即。没有任何内容被过滤。 Lombok 有问题吗?还是定义不正确?

最佳答案

如何序列化对象?你用的是Spring吗?您是否直接使用ObjectMapper

如果您使用 Spring,那么您需要做的是使用 @JsonView(Views.StatusComment.class)@JsonView(Views.PatchComment.class) 注释 Controller 的方法)例如:

用于读取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,那么您需要做的是指定使用的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);

关于java - 将两种不同的 JSON 表示反序列化为一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58234461/

相关文章:

java - 使用 Guava 连接 ImmutableSet

Java 多维数组

java - 当我关闭另一端套接字后,套接字的输入流仍然获取数据

java - 无法在远程服务器上运行 Vaadin 应用程序

java - 使用 mongodb 进行 spring 登录

performance - Jackson 2 : Parsing a ton of classes through JPA associations, 是否可以限制深度?

java - jackson 中用于枚举的自定义xml解串器

java - 如何指示 Spring Autowiring 紧耦合对象链中的字段

spring - 如何访问 JAR 文件中的属性?

java - Spring RestTemplate 在尝试反序列化对象的嵌套列表时返回 null 对象