2016-03-09 22 views
1

我正在使用Json.net序列化器来序列化objects.It正在完美工作。现在根据我的要求,我已经使用JsonDotNetCustomContractResolvers从一个对象中排除属性。但对于下面的show对象,我需要排除它的所有属性。如何在Newtonsoft json中如果跳过序列化对象?

Partial Public Class CreditCard 
    <Key> _ 
    Public Property ID As Integer 
    Public Property CustomerID As Integer 
    Public Property CardType As String 
    Public Property Last4Digit As String 
    Public Property ExpiryDate As String 
    Public Property Token As String 
    Public Property IsPrimary As Boolean 
End Class 

而当我这样做时,我得到了我想要的结果。结果如下图所示。

enter image description here 这里的属性被排除在外,但null对象仍然是序列化的。是否有任何方法可以跳过在Newtonsoft JSON中空对象的序列化。

+0

你的问题有点不清楚。为了澄清,你有'CreditCard'对象列表,并且想要跳过所有属性为'null'的序列化实例,是否正确?'CreditCard'本身非空,对吗? – dbc

+0

此外,为什么您要使用自定义合约解析器?设置['JsonSerializerSettings.N ullValueHandling = NullValueHandling.Ignore'](http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonSerializerSettings_NullValueHandling.htm)?或['DefaultValueHandling = DefaultValueHandling.Ignore'](http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm)? – dbc

+0

是的,我想跳过序列化所有属性为空的实例。 - @ DBC –

回答

1

我写了一个快速测试应用程序,向您展示您可能想要尝试的内容。 对于Json.Net,JsonObject有一个很好的属性,加上设置MemberSerialization.OptIn。这意味着只有JsonProperty的属性才会被序列化。

public class JsonNet_35883686 
{ 
    [JsonObject(MemberSerialization.OptIn)] 
    public class CreditCard 
    { 
     [JsonProperty] 
     public int Id { get; set; } 
     public int CustomerId { get; set; } 
    } 

    public static void Run() 
    { 
     var cc = new CreditCard {Id = 1, CustomerId = 123}; 
     var json = JsonConvert.SerializeObject(cc); 
     Console.WriteLine(json); 

     cc = null; 
     json = JsonConvert.SerializeObject(cc); 
     Console.WriteLine(json); 
    } 
} 

运行的输出是(的原因Id序列化是因为我用JsonProperty

{"Id":1} 
null 

希望这有助于。

相关问题