在将JSON解析为JToken时,如何将所有空字符串更改为null

时间:2018-02-13 04:49:38

标签: c# json

在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"} 
]}

1 个答案:

答案 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"