Newtonsoft.Json序列化双格式化为字符串

时间:2018-04-27 18:36:59

标签: c# .net json.net

我有以下情况:

  • 一个BankAccount对象,DoubleAmount属性为双精度。
  • 我做了一些操作来计算DoubleAmount字段(即聚合等)。
  • 当我把它作为JSON返回到我的前端时,我希望它已经很好地结合了。例如:100.000格式化为100k

为实现这一点,我目前正在做的是以下课程:

public class BankAccount
{
    public string Amount { get; set; } // This is serialized

    // This property is used to do the calculation
    [JsonIgnore]
    public double DoubleAmount { get; set; }

    public void FormatNumbers() {
        // This method is called after I finish doing the calculations
        // with my object and what it basically does is read DoubleAmount,
        // format it and put the value on the Amount string.
    }
}

事情是这堂课感觉不对。我不应该打电话给我FormatNumbers ...我每次更新Amount时都能以某种方式更新我的DoubleAmount,但仍然感觉很奇怪。

无论如何,你们有没有其他更好的方法来实现这个目标? 随意提出任何建议。谢谢!

2 个答案:

答案 0 :(得分:4)

请勿使用 记住的方法来使用,因为这会违反ACID中的 C 一套规则。 C代表"一致性"。如果您有格式化方法,则可以:

account.DoubleAmount = 100000;
account.FormatNumbers();
Console.Write(account.Amount); // "100k" = ok
account.DoubleAmount = 0;
Console.Write(account.Amount); // "100k" = inconsistent = very bad

改为使用自定义getter:

public class BankAccount
{
    [JsonIgnore]
    public double DoubleAmount { get; set; }

    public string FormattedAmount
    {
        get
        {
            return (this.DoubleAmount / 1000).ToString() + "k"; // example
        }
    }
}

如果您使用C#6.0,则此代码会变短:

public class BankAccount
{
    [JsonIgnore]
    public double DoubleAmount { get; set; }
    public string FormattedAmount => $"{this.DoubleAmount / 1000}k";
}

但是,您应该只在动态时,在运行时,只在您需要显示原始,未格式化的值(双重)和格式化(到自定义字符串)时进行序列化(存储离线)。

答案 1 :(得分:1)

JsonConverter的示例用法。请注意,此处的示例转换器仅执行默认的双/字符串转换。您需要实现所需的实际转换。假设您正确实现了转换,此方法适用于序列化和反序列化。

public class BankAccount
{
    [JsonConverter(typeof(DoubleJsonConverter))]
    public double DoubleAmount { get; set; }
}

public class DoubleJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsSubclassOf(typeof(double));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return double.Parse((string)reader.Value);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue($"{value}");
    }
}
相关问题