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

前端 未结 2 1308
庸人自扰
庸人自扰 2020-12-15 19:49

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

相关标签:
2条回答
  • 2020-12-15 20:16

    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>
    
    0 讨论(0)
  • 2020-12-15 20:18

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

    @Id @JsonSerialize(using = ToStringSerializer.class)
    private Long id;
    
    0 讨论(0)
提交回复
热议问题