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

时间:2019-10-04 10:19:31

标签: 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
}

Response

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

但是它完全失败了。它完全失败,即。没有任何东西被过滤。龙目岛有问题吗?还是定义不正确?

1 个答案:

答案 0 :(得分:1)

如何序列化对象?您在使用Spring吗?您是直接使用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,则需要指定使用的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);