0

We have N number of JSON parameters and class properties as well but have to remove dynamically the JSON parameters which are not available in class properties while serializing.

If I use [JsonIgnore] it is only removing values, not the entire property; we need to remove the entire property.

Example:

JSON request:

{
    "Name":"ABC",
    "Age":26,
    "Designation":"Er",
    "Place":"Pune",
    "Gender":"Male"
}

Class:

[Serializable]
public class SampleProperties
{
    [JsonProperty("Name")]
    public string Name { get; set; }
    [JsonProperty("Age")]
    public int Age { get; set; }
    [JsonProperty("Designation")]
    public string Designation { get; set; }
}

Result Expecting :

{
    "Name":"ABC",
    "Age":26,
    "Designation":"Er"
} 
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
lee
  • 21
  • 3
  • Does this question help you? https://stackoverflow.com/questions/44595027/net-core-remove-null-fields-from-api-json-response – Markus Apr 12 '19 at 08:08
  • 1
    Possible duplicate of [.NET Core: Remove null fields from API JSON response](https://stackoverflow.com/questions/44595027/net-core-remove-null-fields-from-api-json-response) – phuzi Apr 12 '19 at 08:11

2 Answers2

1

the best way to do this is to create an object with 30 fields and deserialize the json string to this object
try somthing like this :

class MyObject
{
    public string prop1 {get;set; }
    public string prop2 {get;set; }
}

then :

string json = "your json";
MyObject objectWith30Fields = JsonConvert.DeserializeObject<MyObject>(json);
1

You can set NullValueHandling like the code below that you can see on the documentation of Newtonsoft.Json or in this link as well, in addition, you can use ExpandoObject() as you can see on this link

public class Movie
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string Classification { get; set; }
    public string Studio { get; set; }
    public DateTime? ReleaseDate { get; set; }
    public List<string> ReleaseCountries { get; set; }
}

Movie movie = new Movie();
movie.Name = "Bad Boys III";
movie.Description = "It's no Bad Boys";

string included = JsonConvert.SerializeObject(movie,
    Formatting.Indented,
    new JsonSerializerSettings { });

// {
//   "Name": "Bad Boys III",
//   "Description": "It's no Bad Boys",
//   "Classification": null,
//   "Studio": null,
//   "ReleaseDate": null,
//   "ReleaseCountries": null
// }

string ignored = JsonConvert.SerializeObject(movie,
    Formatting.Indented,
    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

// {
//   "Name": "Bad Boys III",
//   "Description": "It's no Bad Boys"
// }

More about ExpandoObject

Aderbal Farias
  • 989
  • 10
  • 24