5

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)?

2 Answers 2

8

Use JsonIgnore attribute available in Newtonsoft.Json package.

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

Sign up to request clarification or add additional context in comments.

Comments

4

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());

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.