Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

jackson

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, this 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.

like image 455
Ram Patra Avatar asked Aug 07 '16 00:08

Ram Patra


1 Answers

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);
like image 196
Sohlowmawn Avatar answered Nov 05 '22 19:11

Sohlowmawn