重命名Spring中MappingJacksonJsonView使用的JSON字段


问题内容

我正在使用MappingJacksonJsonView将一个类序列化为JSON,但是,我希望能够基于getter名称从默认名称重命名某些字段。

这是因为我必须输出jQuery文件上传之类的字段名称,例如“ delete_url”和“
delete_type”。我正在使用@Jsonserialize注释来手动选择要序列化的字段。

@JsonAutoDetect(getterVisibility = Visibility.NONE)
public interface Picture {

    @JsonSerialize
    String getName();

    @JsonSerialize
    String getDelete_url();

    ...

例如getDelete_url(),当我想调用方法时,我不得不调用它getDeleteUrl(),但是"delete_url"在序列化为JSON时仍会输出密钥。


问题答案:

您应该有资格使用@JsonProperty

@JsonAutoDetect(getterVisibility = Visibility.NONE)
public interface Picture {

  @JsonSerialize
  @JsonProperty("name")
  String getName();

  @JsonSerialize
  @JsonProperty("delete_url")
  String getDeleteUrl();

  //...