Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore c# fields dynamically from Json Serialize

For API purposes I need to ignore some fields based on criteria I receive. Usually I could use [ScriptIgnore] attribute to do this.

But how I can ignore fields dynamically (based on some conditionals)?

like image 714
Vnuuk Avatar asked Nov 16 '15 10:11

Vnuuk


2 Answers

Use JsonIgnore attribute available in Newtonsoft.Json package.

then, if you want it to be dynamically conditional, see ShouldSerialize

like image 174
Paul Avatar answered Nov 14 '22 23:11

Paul


Assuming you use Json.Net, you can create your own converter for a specific type by creating a class that inherits from JsonConverter.

public class MyJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(MyType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var objectToSerialize = new {}; //create the object you want to serialize here, based on your dynamic conditions
        new JsonSerializer().Serialize(writer, objectToSerialize); //serialize the object to the current writer
    }
}

Then you call JsonConvert.DeserializeObject and pass it your custom converter:

JsonConvert.DeserializeObject<MyType>(jsonString, new MyJsonConverter());
like image 24
Domysee Avatar answered Nov 14 '22 23:11

Domysee