Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force Jackson to write numbers as strings when serializing my objects

I have an id that is pretty large on one of my java objects. When it jackson converts it to JSON it sends it down as a number (e.g. {"id":1000110040000000001}) but as soon as it becomes a javascript object the id gets changed to 1000110040000000000. I read about this issue here

It works fine when the id is smaller. My first thought is to just force Jackson to convert all the numbers to strings but I am open to other options as well. If possible I would prefer not to add Jackson annotations to my java objects.

like image 965
testing123 Avatar asked Apr 17 '13 05:04

testing123


People also ask

What is Jackson object serialization?

Jackson is a solid and mature JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON response objects with a lot of flexibility.

Does Jackson use Java serialization?

Note that Jackson does not use java.

How do you serialize an object to JSON Jackson in Java?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


2 Answers

Jackson-databind (at least 2.1.3) provides special ToStringSerializer. That did it for me.

@Id @JsonSerialize(using = ToStringSerializer.class)
private Long id;
like image 137
testing123 Avatar answered Sep 19 '22 07:09

testing123


com.fasterxml.jackson.core:jackson-core:2.5.4 provides JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS for ObjectMapper configuration.

final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);

Foo foo = new Foo(10);
System.out.println("Output: " + objectMapper.writeValueAsString(foo));

Output: {"a":"1"}

class Foo {
    @XmlElement(name = "a")
    Integer a
}

To include the dependency:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.2</version>
</dependency>
like image 38
user770119 Avatar answered Sep 20 '22 07:09

user770119