【问题标题】:Applying a naming strategy to a class name when serializing a POJO with Jackson使用 Jackson 序列化 POJO 时将命名策略应用于类名
【发布时间】:2012-06-09 05:47:24
【问题描述】:

使用 Jackson 的 WRAP_ROOT_VALUE 序列化设置并序列化 POJO 时,类名用作序列化 JSON 中的根值。

mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);

问题 - 如何将命名策略应用于类名?我想将类名转换为其他名称。

【问题讨论】:

    标签: java jackson


    【解决方案1】:

    我的做法是使用@JsonRootName 注释,例如:

    @JsonRootName( value = "smsMessageRequest" )           
    public class TextMessage {
    
        private String message;
        private String address;
    }
    
    public static String toJson(Object object) throws IOException {
    
        ObjectMapper mapper = new ObjectMapper();
    
        mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
        mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
    
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
    }
    

    结果:

    {
      "smsMessageRequest" : {
        "message" : "abc",
        "address" : "123"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 2012-03-20
      • 2019-01-06
      • 2014-10-22
      • 2012-04-07
      相关资源
      最近更新 更多