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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7893619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:52:10  来源:igfitidea点击:

Rename JSON fields used by MappingHymansonJsonView in Spring

javajsonspringspring-mvcHymanson

提问by stivlo

I'm using MappingHymansonJsonView to serialize to JSON a class, however, I'd like to be able to rename some of the fields from the default name based on the getter name.

我正在使用 MappingHymansonJsonView 将类序列化为 JSON,但是,我希望能够根据 getter 名称从默认名称中重命名某些字段。

This is because I've to output field names like "delete_url" and "delete_type" for jQuery file upload. I'm using @Jsonserialize annotation to hand pick the fields to serialize.

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

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

    @JsonSerialize
    String getName();

    @JsonSerialize
    String getDelete_url();

    ...

For instance, I'm forced to call a method getDelete_url(), while I'd like to call it getDeleteUrl(), but still output the key "delete_url"when serializing to JSON.

例如,我被迫调用一个方法getDelete_url(),虽然我想调用它getDeleteUrl(),但"delete_url"在序列化为 JSON 时仍然输出密钥。

回答by nicholas.hauschild

You should be able to qualify using @JsonProperty.

您应该能够使用@JsonProperty.

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

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

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

  //...

回答by Juliano Alves

Have you tried using the @JsonPropertyannotation?

您是否尝试过使用@JsonProperty注释?

"Defines name of the logical property, i.e. Json object field name to use for the property: if empty String (which is the default), will use name of the field that is annotated."

“定义逻辑属性的名称,即用于属性的 Json 对象字段名称:如果为空字符串(这是默认值),将使用被注释的字段的名称。”