GSON - Deserialize case insensitive field name (no definite case pattern)

Viewed 16194

I want to build a flexible api, I have no definite case sensitivity the user can pass, so GSON must be able to deserialize this in case sensitive.

{"firstName":"Juan"}
{"firstname":"Juan"}
{"Firstname":"Juan"}
...

How can I deserialize these field into my Foo's firstName?

public class Foo {
    private String firstName;
    //..getters
}

I tried to use FieldNamingPolicy, but it did not work.

new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .setPrettyPrinting()
            .create();
3 Answers

Not a complete solution to this problem but if the keys happen to be all lowercase such as headimgurl then you can implement FieldNamingStrategy interface

Gson gson = new GsonBuilder().setFieldNamingStrategy(f -> f.getName().toLowerCase()).create();

to parse the value to headImgUrl field of the object.

Related