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.
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.
Note that Jackson does not use 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.
Jackson-databind (at least 2.1.3) provides special ToStringSerializer. That did it for me.
@Id @JsonSerialize(using = ToStringSerializer.class)
private Long id;
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With