[英]Newtonsoft.Json serialize double formated as string
我有以下情況:
DoubleAmount
屬性(是double)的BankAccount
對象。 DoubleAmount
字段(即聚合等)。 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.