Last active
August 29, 2015 14:03
-
-
Save bytenik/d76702eb717497a0a38c to your computer and use it in GitHub Desktop.
Failing example for interface type name handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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