使用Jackson在Java中将带有下划线的JSON去神圣化为骆驼大小写?

2022-09-02 13:59:37

要将具有驼峰大小写属性的 java 对象序列化为带有下划线的 json,我们将其用作 。PropertyNamingStrategySNAKE_CASE

那么,是否也有相反的事情要做。也就是说,将带有下划线的 json 反序列化为具有驼峰大小写的 Java 对象。

例如,此 JSON:

{
    "user_id": "213sdadl"
    "channel_id": "asd213l"
}

应该反化为这个 Java 对象:

public class User {
    String userId; // should have value "213sdadl"
    String channelId; // should have value "asd213l"
}

我知道这样做的一种方法是通过注释在字段级别工作。我有兴趣了解这方面的任何全局设置。@JsonProperty


答案 1

好吧,您可以为 PropertyNamingStrategy 提供一个如下所示的实现:

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) {
        return convert(defaultName);
    }

    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();
    }
}

然后在您的实现或执行反化化的类中,您可以拥有:

ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new CustomNameStrategy());
YourClass yourClass = mapper.readValue(yourJsonString, YourClass.class);

答案 2