1. 程式人生 > 實用技巧 >newtonsoft.json序列化時另命名屬性名並能反序列化

newtonsoft.json序列化時另命名屬性名並能反序列化

public class ReportModel
{
    [JsonProperty("title")]
    public string ProductName { get; set; }
    [JsonProperty("customercount")]
    public int TotalCustomerCount { get; set; }
    [JsonProperty("totalpayment")]
    public decimal TotalPayment { get; set; }
    [JsonProperty("productcount")]
    public int TotalProductCount { get; set; }
}

為屬性新增特性,序列化時json字串中屬性名會變成特性中的字串,同時,也能將Json字串正常的解析成.NET物件。

ReportModel model = new ReportModel() { ProductName = "斐樂", TotalCustomerCount = 20, TotalPayment = 3000, TotalProductCount = 15 };
string json = JsonConvert.SerializeObject(model);
Console.WriteLine(json);
//{"title":"斐樂","customercount":20,"totalpayment":3000.0,"productcount":15}
model = JsonConvert.DeserializeObject<ReportModel>("{ 'title':'斐樂','customercount':20,'totalpayment':3000.0,'productcount':15}");
Console.WriteLine(model.ProductName);
Console.WriteLine(model.TotalCustomerCount);
//{"title":"斐樂","customercount":20,"totalpayment":3000.0,"productcount":15}
//斐樂
//20