简体   繁体   中英

How to map Unrecognised field with codehaus.jackson.map.ObjectMapper

I am kind of stuck with one issue of json String to java object conversion.I understand that using the DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES we can ignore the fields which does not match with the name of the fields in the object.

However is there is a way we can map the fields somehow from the json string to the object,some kind of instruction to the API saying that "If you find X while transformation ,map the value of X to Y"

public class MyPOJO {

    private String id;
    private int name;
    // standard getters and setters 
}

And the JSON String has the name as name2 ,somwehow I want to map the value of name2 to name variable of my pojo .

String jsonAsString = 
        "{\"id\":\"a\"," +
        "\"name2\":\"something\"}";

Thanks.

You can do it by using annotation

For Jackson: Use @JsonProperty

For GSon : Use @SerializedName

public class SampleJSONDTO implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 4694247925037679167L;

    @JsonProperty(value = "leftHand")
    private int left;
    @JsonProperty(value = "rightHand")
    private int right;
    public int getLeft()
    {
        return left;
    }
    public void setLeft(int left)
    {
        this.left = left;
    }
    public int getRight()
    {
        return right;
    }
    public void setRight(int right)
    {
        this.right = right;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM