如何强制 Json.net 中的最小小数位数?

时间:2023-04-24
本文介绍了如何强制 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 对象 下一篇:在 Newtonsoft.Json 库中获取原始 json 字符串

相关文章