Search code examples
javajsonjson-deserialization

Jackson mapping: Deserialization of JSON with different property names


I have a server that returns a json string:

{"pId": "ChIJ2Vn0h5wOlR4RsOSteUYYM6g"}

Now, I can use jackson to deserialize it into an object with the variable called pId, but I don't want the variable to be called pId, I would rather deserialize it to placeId.

Current object in android java:

public class Place {

    private String pId;

}

What I want the object to look like:

public class Place {

    private String placeId;

}

If I change the object's variable to placeId, jackson will not be able to deserialize the JSON as the property names no longer matches.

Is there a jackson annotation I can used to map the "placeId" variable in the java object to the JSON string variable "pId" returned back from the server?


Solution

  • Use @JsonProperty annotation:

    public class Place {
    
        @JsonProperty("pId")
        private String placeId;
    
    }
    

    For more information you can see the related javadoc.