Convert String to Integer using FasterXML Jackson

Lucas Beier picture Lucas Beier · Aug 18, 2015 · Viewed 7.5k times · Source

I'm consuming two JSONs.

The first one has the ID as a String.

"details": {
    "id": "316.0"
}

The other one has the ID as Integer.

"details": {
    "detailId": 316
}

Both JSONs are being mapped with FasterXML to two different classes. I want both ids to be Integer. For now they are String.

How can I force ForceXML to convert "316.0" to Integer so I can compare both attributes easily?

Answer

StaxMan picture StaxMan · Aug 18, 2015

Jackson actually handles coercion, so that if property has type int or java.lang.Integer, it will parse JSON Strings, not just use JSON Numbers. Reverse is possible as well, using @JsonFormat(shape=Shape.STRING) for numeric fields.