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?

Lucas Beier
  • 621
  • 1
  • 7
  • 19

2 Answers2

16

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
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());
Dici
  • 25,226
  • 7
  • 41
  • 82
  • Do you need to use asText(), perhaps there is a method which returns a number. – Peter Lawrey Aug 17 '15 at 22:51
  • 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 :) – Dici Aug 17 '15 at 23:12
  • 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. – Peter Lawrey Aug 18 '15 at 05:11
  • I thought the parse would fail for `"5"` because it is not a numeric field. I'll try that – Dici Aug 18 '15 at 07:50