簡體   English   中英

序列化為JSON時有條件地更改某些屬性的類型

[英]Conditionally change the types of certain properties when serializing to JSON

我有一個自定義類,正在使用JSON.NET對其進行序列化。 在該類中,我們稱其為posInvoice ,我具有諸如TotalAmount UnitPriceQuantityTotalAmount之類的屬性。 當我將序列化的對象作為POST請求發送到端點時,此方法工作正常。

現在,我有另一個端點,它接受相同的類posInvoice 但是,此端點期望這些值改為小數。

在我的代碼中處理此問題的最佳方法是什么? 我應該只創建另一個類並更改屬性類型嗎? 我已經研究並試圖在Stack Overflow中尋找類似的情況,但找不到任何東西。

這是我要采取的方法:

  1. 使用小數定義PosInvoice類,因為這是最適合金額的數據類型。
  2. 創建一個自定義JsonConverter類,可在序列化期間使用該類將小數轉換為字符串。
  3. 將轉換器與需要將金額作為字符串的端點一起使用; 否則省略它。

型號類別:

public class PosInvoice
{
    public string Description { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal Quantity { get; set; }
    public decimal TotalAmount { get; set; }
}

轉換器:

public class InvoiceAmountsAsStringsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(PosInvoice);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        PosInvoice invoice = (PosInvoice)value;
        JsonObjectContract contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(typeof(PosInvoice));
        writer.WriteStartObject();
        foreach (JsonProperty prop in contract.Properties)
        {
            writer.WritePropertyName(prop.PropertyName);
            object propValue = prop.ValueProvider.GetValue(invoice);
            if (propValue is decimal)
            {
                writer.WriteValue(((decimal)propValue).ToString(CultureInfo.InvariantCulture));
            }
            else
            {
                serializer.Serialize(writer, propValue);
            }
        }
        writer.WriteEndObject();
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

用法:

public static string SerializeInvoice(PosInvoice invoice, bool serializeDecimalsAsStrings)
{
    var settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
    if (serializeDecimalsAsStrings)
    {
        settings.Converters.Add(new InvoiceAmountsAsStringsConverter());
    }
    return JsonConvert.SerializeObject(invoice, settings);
}

在這里工作的演示: https : //dotnetfiddle.net/4beAW3

暫無
暫無

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

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