Skip to content

Instantly share code, notes, and snippets.

@bytenik
Last active August 29, 2015 14:03
Show Gist options
  • Save bytenik/d76702eb717497a0a38c to your computer and use it in GitHub Desktop.
Save bytenik/d76702eb717497a0a38c to your computer and use it in GitHub Desktop.
Failing example for interface type name handling
class ContractResolver : DefaultContractResolver
{
public readonly IDictionary<Type, JsonContract> Contracts = new Dictionary<Type, JsonContract>();
public override JsonContract ResolveContract(Type type)
{
if (Contracts.ContainsKey(type))
return Contracts[type];
else
return base.ResolveContract(type);
}
}
interface IInterface { }
class Parent { }
class Class : Parent, IInterface
{
public string String { get; set; }
}
void Main()
{
var resolver = new ContractResolver();
var sett = new JsonSerializerSettings
{
ContractResolver = resolver,
Formatting = Newtonsoft.Json.Formatting.Indented
};
var obj = new { Prop = (IInterface)new Class { String = "Abc" } };
JsonObjectContract contract = (JsonObjectContract)resolver.ResolveContract(obj.GetType());
resolver.Contracts.Add(obj.GetType(), contract);
contract.Properties[0].TypeNameHandling = TypeNameHandling.All;
var json = JsonConvert.SerializeObject(obj, sett);
Console.WriteLine(json);
var deserialized = JsonConvert.DeserializeObject(json, obj.GetType(), sett);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment