繁体   English   中英

使用Jackson进行JSON字符串序列化(驼峰式)和反序列化(来自蛇形)

[英]JSON string serialization ( to camel case ) and deserialization (from snake case )using Jackson

我试图将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"} .

有什么办法可以实现?

我可以根据输入的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;
    }
}

您应该能够通过定义反序列化的创建者来实现这一点,然后让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才能起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM