We have objects which rely on both the ISerializable (to mark the interfaces as serializable for implementers) and internally there are also JsonObject and JsonProperty attributes. As an example:
[JsonObject("Example")]
[Serializable]
public class Example : ISerializable
{
[JsonProperty("TEST")]
string _testString;
public string TestString
{
get => _testString;
set => _testString = value;
}
protected Example(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info), $"{nameof(info)} is null.");
}
_testString = info.GetString(nameof(TestString));
}
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(TestString), _testString);
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info), $"{nameof(info)} is null.");
}
GetObjectData(info, context);
}
}
So is there a way to enforce the Json serializer to use either the ISerializable interface or the attributes. If there is no option to enforce, perhaps there is the option to prioritize the different mechanisms?
Update
Based on one comment below I added a contract resolver but this leads to wrong/missing content in my serialized string - I guess I use the contract resolver in a wrong way?
public class ContractResolver : IContractResolver
{
public JsonContract ResolveContract(Type type)
{
if(typeof(ISerializable).IsAssignableFrom(type))
{
return new JsonISerializableContract(type);
}
return new JsonObjectContract(type);
}
}