I have a class that is a wrapper over a string providing some additional functionality. Among other interfaces it also implements the IEnumerable<char>
interface.
I'd like to be able to serialize it to a string with JsonNet. Because it didn't work and always serialized into an array - I guess because of the IEnumerable<char>
interface, I added the ISerializable
interface. But for some reason JsonNet still creates an array and ignores ISerializable
. Adding the SerializableAttribute
didn't help either.
Here's a small proof of concept code that demonstrates the behaviour (for LINQPad):
void Main()
{
JsonConvert.SerializeObject(new NotACollection("foo")).Dump(); // ["f","o","o"]
}
[Serializable]
class NotACollection : IEnumerable<char>, ISerializable
{
private readonly string _value;
public NotACollection(string value)
{
_value = value;
}
public IEnumerator<char> GetEnumerator()
{
return _value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("_value", _value);
}
public override string ToString()
{
return _value;
}
}
I know I could create a custom JsonCovert
class but since the wrapper is in a library where I don't want to reference JsonNet, I'd prefer another solution.
Am I doing something wrong here? I thought JsonNet would pick the ISerializable
implementation if it's available?
(this class must not implement an implicit conversion to a string because this would defeat its purpose and result in weird bugs)