Newtonsoft Add JSONignore at Runtime

NewtonSoft add JSONIGNORE at runTime

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.

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. I want the Id and Name properties in the serialization output, but I'm definitely not interested in the AlternateName and Color. I've marked those with [JsonIgnore]. I want the description to appear, but sometimes this can get really long, so I've used a custom JsonConverter to limit its length. I also want to use a shorter property name for the description, so I've marked it with [JsonProperty("Desc")].

class Foo
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public string AlternateName { get; set; }
[JsonProperty("Desc")]
[JsonConverter(typeof(StringTruncatingConverter))]
public string Description { get; set; }
[JsonIgnore]
public string Color { get; set; }
}

When I serialize an instance of the above...

Foo foo = new Foo
{
Id = 1,
Name = "Thing 1",
AlternateName = "The First Thing",
Description = "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
Color = "Yellow"
};

string json = JsonConvert.SerializeObject(foo, Formatting.Indented);

...I get this output:

{
"Id": 1,
"Name": "Thing 1",
"Desc": "This is some lengthy text describing Thing 1 "
}

Now, let's say that I sometimes want to get the full JSON output, ignoring my customizations. I can use a custom ContractResolver to programmatically "unapply" the attributes from the class. Here's the code for the resolver:

class IgnoreJsonAttributesResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
foreach (var prop in props)
{
prop.Ignored = false; // Ignore [JsonIgnore]
prop.Converter = null; // Ignore [JsonConverter]
prop.PropertyName = prop.UnderlyingName; // restore original property name
}
return props;
}
}

To use the resolver, I add it to the JsonSerializerSettings and pass the settings to the serializer like this:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new IgnoreJsonAttributesResolver();
settings.Formatting = Formatting.Indented;

string json = JsonConvert.SerializeObject(foo, settings);

The output now includes the ignored properties, and the description is no longer truncated:

{
"Id": 1,
"Name": "Thing 1",
"AlternateName": "The First Thing",
"Description": "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
"Color": "Yellow"
}

Full demo here: https://dotnetfiddle.net/WZpeWt

System.Text.Json add JsonIgnore attribute at runtime

After looking in Custom Converters, already found my answer.

here's my converter

public class DataConverter : JsonConverter<Data>
{
public override Data Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}

public override void Write(Utf8JsonWriter writer, Data value, JsonSerializerOptions options)
{
var properties = value.GetType().GetProperties();

writer.WriteStartObject();

foreach (var prop in properties)
{
if (prop.HasAttribute<ShouldSerializeAttribute>())
{
var acceptedTypes = prop.GetAttributeValue<ShouldSerializeAttribute, string[]>(x => x.AcceptedTypes);
if (acceptedTypes != null && acceptedTypes.Contains(value.Type))
{
var propValue = prop.GetValue(value);
writer.WritePropertyName(prop.Name);
JsonSerializer.Serialize(writer, propValue, prop.PropertyType, options);
}
}
}

writer.WriteEndObject();
}
}

Dynamically ignore the properties on class using json.net

Json.NET has the ability to conditionally serialize properties by placing a ShouldSerialize method on a class.

the following link will give details
http://www.newtonsoft.com/json/help/html/conditionalproperties.htm

Newtonsoft ignore attributes?

I ended up making all properties I needed to only add attributes to virtual, and overriding them alone in another class, with the relevant newtonsoft attributes.

This allows me to have different serialisation behavior when de-serialising from CouchDB and serialising for a GET, without too much dupe. It is fine, and a bonus, that the two are coupled; any changes in the base i would want anyway.

It would still be nice to know if my original question is possible?



Related Topics



Leave a reply



Submit