Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Null values in JSON and Update JSON

Tags:

json

c#

json.net

I have JSON Array as a string by serializing a list using Newtonsoft as below

[{"ID":"1","Name":"somename","Class":"12","Section":null},{"ID":null,"Name":"somename","Class":"13","Section":null},{"ID":2,"Name":"somename","Class":null,"Section":"A"}]

I need to convert this JSON by removing the NULL values to another JSONString like below

[{"ID":"1","Name":"somename","Class":"12",},{"Name":"somename","Class":"13",},{"ID":2,"Name":"somename","Section":"A"}]

Is there a way I can use Newtonsoft for this or how do i do this.

like image 275
user2067567 Avatar asked Dec 16 '22 11:12

user2067567


1 Answers

You can use JsonSerializerSettings with NullValueHandling:

var result = JsonConvert.SerializeObject(obj, 
            new JsonSerializerSettings() 
            { 
                NullValueHandling = NullValueHandling.Ignore 
            });
like image 51
cuongle Avatar answered Dec 28 '22 02:12

cuongle