简体   繁体   中英

How to change all empty strings to null when parsing JSON to a JToken

In C#, using JSON.Net and without using custom classes, how would I convert empty strings to nulls? such that:

{"employees":[
    {"firstname":"", "lastname":"Doe"},
    {"firstname":"Anna", "lastname":""},
    {"firstname":"", "lastname":"Jones"} 
]}

becomes

{"employees":[
    {"firstname":null, "lastname":"Doe"},
    {"firstname":"Anna", "lastname":null},
    {"firstname":null, "lastname":"Jones"} 
]}

You can use DefaultValueHandling options for the JsonSerializer + DefaultValue attribute.

Model example:

public class User 
{
    [DefaultValue("")]
    public string Firstname {get; set; }
    [DefaultValue("")]
    public string Lastname {get; set; }
}

Deserialization usage example:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM