Deserialising JSON with underscores to camel case in Java using Jackson?

Ram Patra :

To serialize java objects with camel case attributes to json with underscore we use PropertyNamingStrategy as SNAKE_CASE.

So, is there something to do the opposite as well. That is, deserialise json with underscore to Java objects with camel case.

For example, JSON:

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

should be deserialised to this Java object:

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

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.

Sohlowmawn :

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

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=450918&siteId=1