2012-05-29 78 views
4

使用反射,我能夠根據它們是繼承,聲明,公共,私人等過濾成員。有什麼辦法可以做同樣的排序使用JSon.NET序列化對象時過濾?序列化爲JSON(使用Json.Net),同時忽略繼承成員

我的代碼是目前:

using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 

public void addRequestParameters<T>(string key, T SerializableRequestParameters) 
{ 
    //Serialize the object 
    string json = JsonConvert.SerializeObject(SerializableRequestParameters, new JsonSerializerSettings 
    { 
     TypeNameHandling = TypeNameHandling.All, 
     ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
    }); 
    //Add it to an existing request (unrelated to this question) 
    ((JObject)JSONRequest).Add(key, JToken.Parse(json)); 
} 

回答

3

我想你可以使用自定義ContractResolver來實現自己的目標。

IContractResolver接口提供了一種方法來定製JsonSerializer如何序列化和反序列化.NET對象爲JSON。

實施IContractResolver接口,然後到JsonSerializer分配一個 比如讓你控制的對象是否是 序列化爲一個JSON對象或JSON數組,應該 被序列化什麼對象的成員,他們是如何系列化,它們是什麼調用。

無論如何,我發現了同樣的問題在這裏:Using JSON.net, how do I prevent serializing properties of a derived class, when used in a base class context?

相關問題