Home >Backend Development >C#.Net Tutorial >C# implements Json serialization method to delete null value example

C# implements Json serialization method to delete null value example

黄舟
黄舟Original
2017-09-15 11:34:132008browse

We want to serialize an object, but if the attributes of the object are null, we want to remove all the attributes that are null. How to deal with it? In fact, the method is very simple. Let’s learn with the editor of Script Home How to remove null values ​​in Json serialization in C

#We want to serialize an object, but if the properties of the object are null, we want to remove all the properties that are null.

Here I useNewtonsoft.Json.dll

Record the serialization and deserialization

json string to object


Model model=JsonConvert.DeserializeObject<Model>(val);

Convert the object into a json format string


string jsonString = JsonConvert.SerializeObject(obj);

So how to serialize to How to filter out NULL when using json? ?


var jsonSetting = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
var json = JsonConvert.SerializeObject(data, Formatting.Indented, jsonSetting);

Directly like thisJsonConvert.SerializeObject(obj);Serialization result


##

"MemberQuery": {
  "PhoneNumber": "13222222222",
  "Name": "test",
  "MF": "女",
  "BirthDate": "01/01/2017",
  "MaritalStatus": null,
  "Country": null
}

Filter out NULL serialization results:


"MemberQuery": {
 "PhoneNumber": "13222222222",
 "Name": "test",
 "MF": "女",
 "BirthDate": "01/01/2017"
}

Summary

The above is the detailed content of C# implements Json serialization method to delete null value example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn