23

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.

Community
  • 1
  • 1
testing123
  • 11,367
  • 10
  • 47
  • 61
  • 1
    Relevant: http://stackoverflow.com/a/12046979/2129835 – thgaskell Apr 17 '13 at 05:39
  • Thanks for pointing that out. Apparently in version 2.1.3 you can do something like this: @JsonSerialize(using = ToStringSerializer.class). It still would be nice if I could just set some overall setting in the object mapper, but this will do if that is not possible. – testing123 Apr 17 '13 at 15:51
  • Possible duplicate of [Jackson JSON custom serialization for certain fields](https://stackoverflow.com/questions/12046786/jackson-json-custom-serialization-for-certain-fields) – Oleg Estekhin Aug 15 '17 at 13:48

2 Answers2

34

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

@Id @JsonSerialize(using = ToStringSerializer.class)
private Long id;
testing123
  • 11,367
  • 10
  • 47
  • 61
21

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>
user770119
  • 422
  • 1
  • 5
  • 11
  • 1
    Thanks! This approach lets me serialize auto-generated classes in the way I want without needing to alter the class definition – Adam Jan 22 '18 at 13:45
  • 1
    in application.properties, you can use `spring.jackson.generator.write-numbers-as-strings=true` – min Dec 13 '18 at 03:51
  • The syntax has changed. It's deprecated to use `JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS` or to use `mapper.configure()`. I'm trying to figure out the latest syntax. – gene b. Mar 13 '23 at 21:36