Convert String to Integer using FasterXML Jackson
Asked Answered
N

2

8

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?

Nembutal answered 17/8, 2015 at 22:25 Comment(0)
M
17

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.

Macleod answered 18/8, 2015 at 3:30 Comment(0)
B
2

Since you don't always have the same format, the best way to do it is to retrieve it as a string and parse it :

int detailId = (int) Float.parseFloat(node.path("details").asText());
Blankbook answered 17/8, 2015 at 22:28 Comment(4)
Do you need to use asText(), perhaps there is a method which returns a number.Provender
Yes there is, but his format does not allow is since it he has sometimes integers, sometimes strings. Or am I mistaken ? You seem to imply the contrary :)Blankbook
I think the OP wants to be able able to ignore the ". I would use a method which returns a double and cast that. Possibly with some rounding.Provender
I thought the parse would fail for "5" because it is not a numeric field. I'll try thatBlankbook

© 2022 - 2024 — McMap. All rights reserved.