Serialize only interface properties to JSON with Json.net

前端 未结 9 1951
孤街浪徒
孤街浪徒 2020-12-08 19:50

With a simple class/interface like this

public interface IThing
{
    string Name { get; set; }
}

public class Thing : IThing
{
    public int Id { get; se         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 20:11

    Improved version with nested interfaces + support for xsd.exe objects

    Yet another variation here. The code came from http://www.tomdupont.net/2015/09/how-to-only-serialize-interface.html with the following improvements over other answers here

    • Handles hierarchy, so if you have an Interface2[] within an Interface1 then it will get serialized.
    • I was trying to serialize a WCF proxy object and the resultant JSON came up as {}. Turned out all properties were set to Ignore=true so I had to add a loop to set them all to not being ignored.

      public class InterfaceContractResolver : DefaultContractResolver
      {
          private readonly Type[] _interfaceTypes;
      
          private readonly ConcurrentDictionary _typeToSerializeMap;
      
          public InterfaceContractResolver(params Type[] interfaceTypes)
          {
              _interfaceTypes = interfaceTypes;
      
              _typeToSerializeMap = new ConcurrentDictionary();
          }
      
          protected override IList CreateProperties(
              Type type,
              MemberSerialization memberSerialization)
          {
              var typeToSerialize = _typeToSerializeMap.GetOrAdd(
                  type,
                  t => _interfaceTypes.FirstOrDefault(
                      it => it.IsAssignableFrom(t)) ?? t);
      
              var props = base.CreateProperties(typeToSerialize, memberSerialization);
      
              // mark all props as not ignored
              foreach (var prop in props)
              {
                  prop.Ignored = false;
              }
      
              return props;
          }
      }
      

提交回复
热议问题