![](/img/trans.png)
[英]Skip Serializing the the Property Name for a JSON Object using Newtonsoft.Json
[英]How to skip serializing an object if it null in Newtonsoft json?
我正在使用Json.net序列化程序对对象进行序列化。它工作正常。现在根据我的要求,我已经使用JsonDotNetCustomContractResolvers从对象中排除属性。但是对于以下show对象,我需要排除其所有属性。
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
当我这样做时,我会得到想要的结果。 结果如下图所示。
这里的属性被排除在外,但是null对象仍然是序列化的。有什么方法可以跳过newtonsoft JSON中null对象的序列化。
我写了一个快速测试应用程序,向您展示了您可能想尝试的内容。 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);
}
}
run的输出是(将Id
序列化的原因是因为我使用了JsonProperty
{"Id":1}
null
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.