我有一个这样的课程:
public class Products
{
public string name {get; set;}
public string CustomName {get; set;}
}
然后我创建了这个:
Product product = new Product();
product.Name = "Apple";
然后使用JSON.Net
执行此操作string json = JsonConvert.SerializeObject(product);
我想要发生的是,如果自定义名称未设置为product.Customname = "CustomApple";
而不显示在JSON中,因为现在如果未设置它仍然显示为'CustomName': 'null'
但如果不是我不要让它完全显示只显示像product.Name
我尝试将其更改为私有,但无法再将其设置为
public class Products
{
public private name {get; set;}
public private CustomName {get; set;}
}
我怎么能这样做?
答案 0 :(得分:4)
尝试使用JsonSerializerSettings。
JsonConvert.SerializeObject(product, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
如果只想要指定的变量(如果为null),则使用:
public class Products
{
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
public string name {get; set;}
[JsonProperty]
public string CustomName {get; set;}
}