如何强制 Jackson 在序列化对象时将数字写入字符串
2022-09-02 05:24:30
Jackson-databind(至少 2.1.3)提供了特殊的 ToStringSerializer。这为我做到了。
@Id @JsonSerialize(using = ToStringSerializer.class)
private Long id;
com.fasterxml.jackson.core:jackson-core:2.5.4
提供了配置JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS。ObjectMapper
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));
输出: {“a”:“1”}
class Foo {
@XmlElement(name = "a")
Integer a
}
要包含依赖项,请执行以下操作:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.2</version>
</dependency>