Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Integer using FasterXML Jackson

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?

like image 889
Lucas Beier Avatar asked Aug 17 '15 22:08

Lucas Beier


People also ask

What is FasterXML in Java?

FasterXML is the business behind the Woodstox streaming XML parser, Jackson streaming JSON parser, the Aalto non-blocking XML parser, and a growing family of utility libraries and extensions. FasterXML offers consulting services for adoption, performance tuning, and extension.

How to parse JSON in Java using fasterxml/Jackson?

Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object, jackson-databind library will be use for the implementation. ? That’s all for how to parse JSON in Java using fasterXML / jackson-databind lib.

Is Jackson converting numbers to strings by default?

Sign in to your account By default, Jackson is converting numbers to strings. In most cases, that's fine. But not in my situation unfortunately. Is there a way to prevent that?

How to convert XML file to string in Java?

Likewise, if we have an XML file, we can convert it back to a Java object. Here, we first read the file into an input stream and then convert the input stream to a String with a simple utility method.

How to convert a string to an integer in Java?

Next, we will consider how to convert a string to an integer using the Integer.valueOf () method. 2. Use Integer.valueOf () to Convert a String to an Integer. This method returns the string as an integer object. If you look at the Java documentation, Integer.valueOf () returns an integer object which is equivalent to a new Integer ...


1 Answers

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.

like image 99
StaxMan Avatar answered Oct 14 '22 10:10

StaxMan