如何在运行时选择要为JSON对象序列化的属性?

时间:2015-06-26 14:04:03

标签: c# json serialization

我有一个具有多个属性的对象:

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()方法,但我不知道该方法应该检查什么。

1 个答案:

答案 0 :(得分:0)

我提出的解决方案涉及使用反射来获取对象的属性列表,并将用户未列出的属性值更改为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; }