使用Jackson将带有下划线的JSON反序列化为Java中的驼峰案例? [英] Deserialising JSON with underscores to camel case in Java using Jackson?
问题描述
要使用下划线将具有camel case属性的java对象序列化为json,我们使用 PropertyNamingStrategy
作为 SNAKE_CASE
。
To serialize java objects with camel case attributes to json with underscore we use PropertyNamingStrategy
as SNAKE_CASE
.
那么,是否还有相反的事情要做。也就是说,使用下划线将json反序列化为带有驼峰的Java对象。
So, is there something to do the opposite as well. That is, deserialise json with underscore to Java objects with camel case.
例如,
JSON:
For example, JSON:
{
"user_id": "213sdadl"
"channel_id": "asd213l"
}
应反序列化为此Java对象:
should be deserialised to this Java object:
public class User {
String userId; // should have value "213sdadl"
String channelId; // should have value "asd213l"
}
我知道一种方法,这是通过 @JsonProperty
注释,适用于现场级别。我有兴趣了解任何全局设置。
I know one way of doing this which is via @JsonProperty
annotation which works at field level. I am interested in knowing any global setting for this.
推荐答案
您可以拥有PropertyNamingStrategy的实现,如下所示:
Well you can have an implementation for PropertyNamingStrategy that looks something like this:
import org.codehaus.jackson.map.MapperConfig;
import org.codehaus.jackson.map.PropertyNamingStrategy;
import org.codehaus.jackson.map.introspect.AnnotatedField;
import org.codehaus.jackson.map.introspect.AnnotatedMethod;
public class CustomNameStrategy extends PropertyNamingStrategy
{
@Override
public String nameForField(MapperConfig
config,
AnnotatedField field, String defaultName) {
return convert(defaultName);
}
@Override
public String nameForGetterMethod(MapperConfig
config,
AnnotatedMethod method, String defaultName) {
return convert(defaultName);
}
@Override
public String nameForSetterMethod(MapperConfig
config,
AnnotatedMethod method, String defaultName) {
String a = convert(defaultName);
return a;
}
public String convert(String defaultName )
{
char[] arr = defaultName.toCharArray();
StringBuilder nameToReturn = new StringBuilder();
for(int i=0; i< arr.length(); i++){
if(arr[i] == '_'){
nameToReturn.append(Character.toUpperCase(arr[i+1]));
i++;
}else{
nameToReturn.append(arr[i]);
}
}
return nameToReturn.toString();
}
}
然后在您的实施或课程中你可以进行反序列化:
then in your implementation or the class that does the desrialization you can have:
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new CustomNameStrategy());
YourClass yourClass = mapper.readValue(yourJsonString, YourClass.class);
这篇关于使用Jackson将带有下划线的JSON反序列化为Java中的驼峰案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!