Search code examples
javajsonboon

Boon JSON - Change Field Name for Object Deserialization


I am using Boon JSON and I'd like to change the name of a field on a class that is being generated from JSON.

I just want to change

{"first_name": "Cristine", "last_name": "McVie"}

So it maps to the Java fields:

String firstName;
String lastName;

I've already got everything working (ie, if I use camel-case in the JSON, the object is created properly.


I've tried the @JsonPropery and (based on the suggestion in comments) the @Named annotations on the class, like so:

public class Person {
    @Named("first_name")
    private String firstName;
    @Named("first_name")
    public String getFirstName() {
        return firstName;
    }
    @Named("first_name")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

Just for edification, this is why I didn't see @JsonProperty working at first. This app is running in Eclipse debug mode, and I was trusting Eclipse to redeploy the updated code, but adding an annotation is apparently NOT enough to trigger the update. Had to restart the app to pick it up.


Solution

  • You need to add either a SerializedName annotation (like GSON) or aJsonProperty annotation (like Jackson) to the fields, like so:

    import org.boon.json.annotations.JsonProperty;
    import org.boon.json.annotations.SerializedName;
    
    public static class Person {
        @SerializedName("first_name")
        String firstName;
    
        @JsonProperty("last_name")
        String lastName;
    }
    

    You can see another example in the documentation.