擅长:python、mysql、java
<p>它不是最漂亮的,但如果你坚持使用json,我们可以创建一个自定义解码器,并让我们的编码器在处理十进制数据时指定类型。在</p>
<pre><code>class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return {
"_type": "decimal",
"value": str(obj)
}
return super(DecimalEncoder, self).default(obj)
</code></pre>
<p>上面的代码添加decimal类型作为解码器的标志,并将decimal编码为字符串以保持精度。在</p>
^{pr2}$
<p>解码器检查decimal类型标志,如果是,则使用decimal构造函数。对于所有其他实例,它使用默认解码</p>
<pre><code>input = { 'prc' : decimal.Decimal('999999.99990000005')}
encoded = json.dumps(input, cls=DecimalEncoder)
decoded = json.loads(encoded, cls=DecimalDecoder)
</code></pre>
<p>最终结果应该接受我们的输入,对其进行编码,并将结果解码为十进制对象。在</p>