How can I force a minimum number of decimal places in Json.net?(如何强制 Json.net 中的最小小数位数?)
问题描述
当我使用 json.net 将小数写入 json 时,我遇到了烦人的不一致问题.有时是 1 dp,有时是 2.
I'm getting an annoying inconsistency when I'm writing decimals to json using json.net. Sometimes it's to 1 dp, other times 2.
显然,我知道将小数输出到具有一定小数位数的字符串的解决方案,例如 this,但是我猜如果不编写自定义序列化程序,您就无法使用 json.net 进行控制.
Obviously I'm aware of solutions to output decimals to strings with a certain number of decimals such as this, but you don't have that control using json.net without writing a custom serializer I guess.
我也知道 Math.Round
强制最大小数位数,这个问题与强制最小小数位数有关.
I am also aware of Math.Round
to enforce a maximum number of decimal places, this question relates to enforcing a minimum number of decimal places.
前两个测试显示发生了什么,它保留了声明或计算的原始小数位数.
The first two tests show what is happening, it is keeping the original number of decimal places from the declaration or calculation.
我发现我可以添加然后减去接下来的两个测试显示有效的一小部分,但是有更清洁的方法吗?
I found I can add and then subtract a small fraction which the next two tests show working, but is there a cleaner way?
[TestFixture]
public sealed class DecimalPlaces
{
public class JsonType
{
public decimal Value { get; set; }
}
[Test]
public void TwoDp()
{
var obj = new JsonType { Value = 1.00m };
Assert.AreEqual("{"Value":1.00}", JsonConvert.SerializeObject(obj));
}
[Test]
public void OneDp()
{
var json = new JsonType { Value = 1.0m };
Assert.AreEqual("{"Value":1.0}", JsonConvert.SerializeObject(obj));
}
private decimal ForceMinimumDp(decimal p, int minDecimalPlaces)
{
decimal smallFrac = 1m/((decimal)Math.Pow(10, minDecimalPlaces));
return p + smallFrac - smallFrac;
}
[Test]
public void ForceMinimumTwoDp()
{
var obj = new JsonType { Value = ForceMinimumDp(1.0m, 2) };
Assert.AreEqual("{"Value":1.00}", JsonConvert.SerializeObject(obj));
}
[Test]
public void ForceMinimumThreeDp()
{
var obj = new JsonType { Value = ForceMinimumDp(1.0m, 3) };
Assert.AreEqual("{"Value":1.000}", JsonConvert.SerializeObject(obj));
}
}
推荐答案
您可以使用自定义 JSON 转换器来实现:
You can do it with a custom JSON converter:
class DecimalJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof (decimal);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(((decimal) value).ToString("F2", CultureInfo.InvariantCulture));
}
}
这是一个非常基本的转换器.您可能需要扩展它以支持其他浮点类型,甚至可能还支持整数类型.
This is a very basic converter. You may need to extend it to support other floating-point types, or perhaps even integer types too.
现在实例化您的序列化器并将您的自定义转换器传递给它,如下所示:
Now instantiate your serialiser and pass it your custom converter, like so:
var serializer = new JsonSerializer();
serializer.Converters.Add(new DecimalJsonConverter());
这篇关于如何强制 Json.net 中的最小小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何强制 Json.net 中的最小小数位数?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01