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

黄舟
Release: 2017-09-15 11:34:13
Original
2000 people have browsed it

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);
Copy after login

Convert the object into a json format string


string jsonString = JsonConvert.SerializeObject(obj);
Copy after login

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);
Copy after login

Directly like thisJsonConvert.SerializeObject(obj);Serialization result


##

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

Filter out NULL serialization results:


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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template