Reputation: 7555
I am using Newtonsoft.Json to serialize a class and all of its members. There is one particular class that many of its members are an instance of, I'd simply like to tell a class to not be serialized at all, so if any member that is an instance of that type is skipped.
Is this possible in C# by appending some sort of attribute to a class to mark it as non-serializable?
Upvotes: 3
Views: 1281
Reputation: 2119
I do not think this can be done using an attribute on the class. However you should be able to do it by implementing a custom JsonConverter
which always serializes and deserializes any instance of this class to null
. This code implements such behavior:
class IgnoringConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteNull();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return null;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ClassToIgnore);
}
}
In this example, ClassToIgnore
is the class you wish to ignore during serialization. Such classes should be decorated with the JsonConverter
attribute:
[JsonConverter(typeof(IgnoringConverter))]
class ClassToIgnore
You can also register the converter as a default converter which is useful if you're using ASP.NET Web API.
I have included a Console application sample to demonstrate the functionality:
using System;
using Newtonsoft.Json;
/// <summary>
/// Class we want to serialize.
/// </summary>
class ClassToSerialize
{
public string MyString { get; set; } = "Hello, serializer!";
public int MyInt { get; set; } = 9;
/// <summary>
/// This will be null after serializing or deserializing.
/// </summary>
public ClassToIgnore IgnoredMember { get; set; } = new ClassToIgnore();
}
/// <summary>
/// Ignore instances of this class.
/// </summary>
[JsonConverter(typeof(IgnoringConverter))]
class ClassToIgnore
{
public string NonSerializedString { get; set; } = "This should not be serialized.";
}
class IgnoringConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteNull();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return null;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ClassToIgnore);
}
}
class Program
{
static void Main(string[] args)
{
var obj = new ClassToSerialize();
var json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
obj = JsonConvert.DeserializeObject<ClassToSerialize>(json);
// note that obj.IgnoredMember == null at this point
Console.ReadKey();
}
}
Upvotes: 4