【问题标题】: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;
}
}