防止NewtonSoft Json添加尾随0 [英] Prevent NewtonSoft Json from adding trailing 0

查看:79
本文介绍了防止NewtonSoft Json添加尾随0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了NewtonSoft.Json库的意外问题.似乎在没有小数部分的十进制值上添加了尾随0:

I am facing an unexpected problem with the NewtonSoft.Json library. It appears it adds a trailing 0 to decimal values that do not have a decimal part:

JsonConvert.SerializeObject(1m)

将返回以下字符串:"1.0".

尽管在很多情况下这不是问题,但就我而言,我确实关心用户提供的精度.如果用户输入1,则需要在数据库中存储1.如果他提供了1.0,那么我需要存储1.0.

While it is not an issue in many cases, in my case, I do care about the precision the users are providing. If a user enters 1, I need to store 1 in my database. If he provides 1.0 then I need to store 1.0.

我使用的是库的最新版本:12.0.3,但是我尝试使用所有以前的主要版本,直到9.0.1,它们都产生相同的结果.

I am using the last version of the library: 12.0.3, but I tried with all the previous major versions down to 9.0.1, and they all produces the same result.

我已经看到了几个关于库删除尾随0的问题(报告为错误,已在11.X版中修复),但是没有关于添加一个的问题.

I have seen several questions about the library removing trailing 0 (reported as a bug, fixed in version 11.X), but none about adding one.

这是我应该报告的错误吗? 如何覆盖此默认行为?

Is this a bug I should report? How can I override this default behavior?

推荐答案

这不是错误,它是库的工作方式.如果要覆盖此行为,则需要一个自定义类型转换器,例如:

It is not a bug, it's how the library works. If you want to override this behaviour, you will need a custom type converter, for example:

public class DecimalJsonConverter : JsonConverter<decimal>
{
    public override decimal ReadJson(JsonReader reader, Type objectType, 
        decimal existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, 
        decimal value, JsonSerializer serializer)
    {
        // Customise how you want the decimal value to be output in here
        // for example, you may want to consider culture
        writer.WriteRawValue(value.ToString());
    }
}

现在像这样序列化:

var settings = new JsonSerializerSettings
{
    Converters = new[] { new DecimalJsonConverter() }
};

var json = JsonConvert.SerializeObject(1m, settings);

这篇关于防止NewtonSoft Json添加尾随0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆