【问题标题】:JSON string serialization ( to camel case ) and deserialization (from snake case )using JacksonJSON字符串序列化(骆驼案例)和反序列化(蛇案例)使用杰克逊
【发布时间】:2015-05-27 16:24:45
【问题描述】:

我正在尝试将 json 字符串反序列化为 POJO,然后使用 Jackson 将其序列化回 json 字符串,但在此过程中,我希望生成的 json 字符串更改键值。

例如输入json字符串:

{"some_key":"value"} 

这是我的 POJO 的样子

public class Sample {    
    @JsonProperty("some_key")
    private String someKey;         
    public String getSomeKey(){
        return someKey ;
    };
}

当我再次序列化它时,我希望 json 字符串是这样的

{"someKey":"value"} .

有什么方法可以实现吗?

【问题讨论】:

    标签: java json serialization jackson json-deserialization


    【解决方案1】:

    您应该能够通过定义反序列化的创建者来实现这一点,然后让 Jackson 执行其默认的序列化行为。

    public class Sample {    
        private final String someKey;
    
        @JsonCreator
        public Sample(@JsonProperty("some_key") String someKey) {
            this.someKey = someKey;
        }
    
        // Should serialize as "someKey" by default
        public String getSomeKey(){
            return someKey;
        }
    }
    

    您可能需要在 ObjectMapper 上禁用 MapperFeature.AUTO_DETECT_CREATORS 才能使其正常工作。

    【讨论】:

      【解决方案2】:

      我能够通过根据输入的 json 字符串重命名 setter 函数来进行反序列化。

      class Test{
          private String someKey;
          // for deserializing from field "some_key"
          public void setSome_key( String someKey) {
             this.someKey = someKey;
          }
      
      
          public String getSomeKey(){
              return someKey;
          }
      }
      

      【讨论】:

      • 虽然这在技术上可行,但您的方法名称不遵循 Java bean 命名约定(请参阅download.oracle.com/otn-pub/jcp/… 中的第 8.8 节)。这可能会导致与其他框架的兼容性问题,如果您的工作将由其他开发人员维护,可能会导致混乱。
      猜你喜欢
      • 2019-08-07
      • 2015-02-01
      • 2017-08-22
      • 2019-05-15
      • 1970-01-01
      • 2015-04-07
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多