簡體   English   中英

Newtonsoft.Json序列化雙精度格式為字符串

[英]Newtonsoft.Json serialize double formated as string

我有以下情況:

  • 一個具有DoubleAmount屬性(是double)的BankAccount對象。
  • 我執行一些操作以計算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 ...每當我更新DoubleAmount ,我都可以以某種方式更新Amount ,但仍然感覺很奇怪。

無論如何,你們是否知道實現此目標的其他更好方法? 隨時提出任何建議。 謝謝!

不要使用必須 記住要使用的方法,因為這違反了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";
}

盡管如此,您僅應在運行時(僅在需要顯示它們時)才即時對原始,未格式化的值(雙精度)和格式(對自定義字符串)進行序列化(存儲脫機)。

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}");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM