当通过as_json运行时,模型中值为1456299399553483799的大整数列将转换为1456299399553483800这样的值。
在序列化bigint时,有没有一种简单的/内置的方法将数字转换为字符串,以避免截断?
发布于 2017-09-16 17:18:23
一种可能的解决方案--我添加了以下代码作为初始化器:
# config/initializers/bigint_serializer.rb
class Integer
def as_json(options = nil)
self > 2147483647 ? self.to_s : self
end
end这将覆盖https://github.com/rails/rails/blob/v5.1.4/activesupport/lib/active_support/core_ext/object/json.rb#L95中Numeric#as_json的默认行为,并导致大于4字节有符号最大整型的数字被转换为字符串。
注意,我非常确定在切换到字符串之前,您实际上可以使用更大的int值--可能是9007199254740991,但我将其保留为最大4字节int,因为我不需要更小的int作为int(请参阅What is JavaScript's highest integer value that a Number can go to without losing precision?)
https://stackoverflow.com/questions/42408072
复制相似问题