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"
} 
2

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.