javascript 序列化对象时,如何强制杰克逊将数字写为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16052314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I force Hymanson to write numbers as strings when serializing my objects
提问by testing123
I have an id that is pretty large on one of my java objects. When it Hymanson 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
我的一个 java 对象上有一个非常大的 id。当 Hymanson 将其转换为 JSON 时,它会将其作为数字发送(例如 {"id":1000110040000000001}),但一旦它成为 javascript 对象,id 就会更改为 1000110040000000000。我在这里阅读了有关此问题的信息
It works fine when the id is smaller. My first thought is to just force Hymanson to convert all the numbers to strings but I am open to other options as well. If possible I would prefer not to add Hymanson annotations to my java objects.
当 id 较小时它工作正常。我的第一个想法是强迫Hyman逊将所有数字转换为字符串,但我也愿意接受其他选择。如果可能的话,我不想将 Hymanson 注释添加到我的 java 对象中。
回答by testing123
Hymanson-databind (at least 2.1.3) provides special ToStringSerializer. That did it for me.
Hymanson-databind(至少 2.1.3)提供了特殊的 ToStringSerializer。那是为我做的。
@Id @JsonSerialize(using = ToStringSerializer.class)
private Long id;
回答by user770119
com.fasterxml.Hymanson.core:Hymanson-core:2.5.4
provides
JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS for ObjectMapper
configuration.
com.fasterxml.Hymanson.core:Hymanson-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));
Output: {"a":"1"}
输出:{"a":"1"}
class Foo {
@XmlElement(name = "a")
Integer a
}
To include the dependency:
要包含依赖项:
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-core</artifactId>
<version>2.7.2</version>
</dependency>