[英]How do I choose which properties to serialize for a JSON object at runtime?
我有一個具有幾個屬性的對象:
public class Contacts
{
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public string City { get; set; }
[JsonProperty]
public string State { get; set; }
[JsonProperty]
public string CompanyType { get; set; }
[JsonProperty]
public string Url { get; set; }
[JsonProperty]
public string PKey { get; set; }
[JsonProperty]
public string SubscriptionDate { get; set; }
}
在我的Web服務中,使用Newtonsoft.Json中的方法對該對象的數組進行序列化並將其作為JSON提供給客戶端:
context.Response.Write(JsonConvert.SerializeObject(new { ContactsArray = contactsArray }));
我想更改我的服務,以便客戶端可以指定他們要序列化的字段,以便他們將請求發送為:
http://myservice.com?fields=Name,City,State
僅名稱,城市和州將被序列化,但是我不知道該如何即時進行。
我讀到了ShouldSerialzeProperty()
方法,但是我不知道我應該在該方法中檢查什么。
我想出的解決方案包括使用反射獲取對象上的屬性列表,並將用戶未列出的屬性的值更改為null:
string[] fields = context.Request.QueryString["Fields"].Split(',');
string[] properties = typeof(Contacts).GetProperties().Select(r => r.Name).ToArray();
fields = properties.Where(r => !fields.Contains(r)).ToArray();
foreach (string field in fields)
{
foreach (Contacts item in contactsArray)
{
item.GetType().GetProperty(field).SetValue(item, null)
}
}
我不確定使用反射是否是最佳實踐,但我想編寫此代碼,以便無論我如何更改數據對象都可以使用它。
然后,我在數據對象中使用了ShouldSerializeProperty()
方法來檢查該值是否為null。 如果為null,則該屬性不會序列化。 例如,對於City Property:
public bool ShouldSerializeCity() { return !(City == null); }
[JsonProperty]
public string City { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.