SoFunction
Updated on 2025-03-06

Method for removing null values ​​in Json serialization in C#

To serialize an object, but if the object's attribute is null, we want to remove all attributes null.

Here I use

Record serialization and deserialization

json string to object

Model model=<Model>(val);

Convert object to json format string

string jsonString = (obj);

So how do I filter out NULL when serializing to json? ?

var jsonSetting = new JsonSerializerSettings {NullValueHandling = };
var json = (data, , jsonSetting);

Just like this(obj);Serialization results

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

Filter out NULL serialization results:

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

Summarize

The above is the method of removing null values ​​in Json serialization in C# introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!