4

One field in the json passed to me is different from the field name of the Java object that I want to deserialize this json into. Suppose I want to deserialize:

{"bag": "LV"}

into

Class MyClass {
    String backpack;
}

So the field backpack should have value LV after deserialization.

The issue is MyClass is from a library that I cannot change or add annotations. Nor do I have any control over the json passed to me. I wonder how I can configure Gson to do it. All the other fields match perfectly.

J Freebird
  • 3,664
  • 7
  • 46
  • 81
  • 1
    Seems you will need to write a custom deserializer - luckily, there is a discussion exactly about [How to write a custom JSON deserializer for Gson](http://stackoverflow.com/questions/6096940/how-do-i-write-a-custom-json-deserializer-for-gson) - give it a shot and let us know if this helps. It does seem like what you are looking for. – ishmaelMakitla Aug 02 '16 at 21:55
  • Switch to Jackson and use mixins. – Sotirios Delimanolis Aug 02 '16 at 22:00

1 Answers1

3
class CustomStrategy implements FieldNamingStrategy {

    @Override
    public String translateName(Field field) {
        if (field.getName().equals("backpack")) {
            return "bag";
        }
        return field.getName();
    }
}

Gson gson = new GsonBuilder().setFieldNamingStrategy(new CustomStrategy()).create();
J Freebird
  • 3,664
  • 7
  • 46
  • 81