Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NewtonSoft add JSONIGNORE at runTime

Am looking to Serialize a list using NewtonSoft JSON and i need to ignore one of the property while Serializing and i got the below code

public class Car
{
  // included in JSON
  public string Model { get; set; }
  // ignored
  [JsonIgnore]
  public DateTime LastModified { get; set; }
}

But am using this Specific class Car in many places in my application and i want to Exclude the option only in one place.

Can i dynamically add [JsonIgnore] in the Specific Place where i need ? How do i do that ?

like image 541
Peru Avatar asked Aug 06 '14 10:08

Peru


People also ask

What is JsonIgnore C#?

Ignore individual properties You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored. If no Condition is specified, this option is assumed.

Can I optionally turn off the JsonIgnore attribute at runtime?

Yes, this can be done using a custom ContractResolver . You didn't show any code, so I'll just make up an example. Let's say I have a class Foo as shown below.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.


2 Answers

No need to do the complicated stuff explained in the other answer.

NewtonSoft JSON has a built-in feature for that:

public bool ShouldSerializeINSERT_YOUR_PROPERTY_NAME_HERE()
{
    if(someCondition){
        return true;
    }else{
        return false;
    }
}

It is called "conditional property serialization" and the documentation can be found here.

Warning: first of all, it is important to get rid of [JsonIgnore] above your {get;set;} property. Otherwise it will overwrite the ShouldSerializeXYZ behavior.

like image 118
Xavier Peña Avatar answered Oct 08 '22 21:10

Xavier Peña


I think it would be best to use a custom IContractResolver to achieve this:

public class DynamicContractResolver : DefaultContractResolver
{
    private readonly string _propertyNameToExclude;

    public DynamicContractResolver(string propertyNameToExclude)
    {
        _propertyNameToExclude = propertyNameToExclude;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

        // only serializer properties that are not named after the specified property.
        properties =
            properties.Where(p => string.Compare(p.PropertyName, _propertyNameToExclude, true) != 0).ToList();

        return properties;
    }
}

The LINQ may not be correct, I haven't had a chance to test this. You can then use it as follows:

string json = JsonConvert.SerializeObject(car, Formatting.Indented,
   new JsonSerializerSettings { ContractResolver = new DynamicContractResolver("LastModified") });

Refer to the documentation for more information.

like image 22
Underscore Avatar answered Oct 08 '22 21:10

Underscore