Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize only interface properties to JSON with Json.net

With a simple class/interface like this

public interface IThing {     string Name { get; set; } }  public class Thing : IThing {     public int Id { get; set; }     public string Name { get; set; } } 

How can I get the JSON string with only the "Name" property (only the properties of the underlying interface) ?

Actually, when i make that :

var serialized = JsonConvert.SerializeObject((IThing)theObjToSerialize, Formatting.Indented); Console.WriteLine(serialized); 

I get the full object as JSON (Id + Name);

like image 766
eka808 Avatar asked Jun 15 '13 12:06

eka808


1 Answers

The method I use,

public class InterfaceContractResolver : DefaultContractResolver {     private readonly Type _InterfaceType;     public InterfaceContractResolver (Type InterfaceType)     {         _InterfaceType = InterfaceType;     }      protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)     {         //IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);         IList<JsonProperty> properties = base.CreateProperties(_InterfaceType, memberSerialization);         return properties;     } }  // To serialize do this: var settings = new JsonSerializerSettings() {      ContractResolver = new InterfaceContractResolver (typeof(IThing)) }); string json = JsonConvert.SerializeObject(theObjToSerialize, settings); 
like image 162
user3161686 Avatar answered Sep 26 '22 07:09

user3161686