在C#中,使用JSON.Net而不使用自定义类,如何将空字符串转换为空值?这样:
{"employees":[
{"firstname":"", "lastname":"Doe"},
{"firstname":"Anna", "lastname":""},
{"firstname":"", "lastname":"Jones"}
]}
变为
{"employees":[
{"firstname":null, "lastname":"Doe"},
{"firstname":"Anna", "lastname":null},
{"firstname":null, "lastname":"Jones"}
]}
答案 0 :(得分:0)
您可以将DefaultValueHandling选项用于JsonSerializer + DefaultValue属性。
模型示例:
public class User
{
[DefaultValue("")]
public string Firstname {get; set; }
[DefaultValue("")]
public string Lastname {get; set; }
}
反序列化用法示例:
var json = "{\"firstname\":\"\", \"lastname\":\"Doe\"}";
var obj = JsonConvert.DeserializeObject<User>(json, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Console.WriteLine(obj.Firstname == null); // print out "True"
Console.WriteLine(obj.Firstname == string.Empty); //print out "False"