实现DefaultContractResolver以包含某些属性

时间:2014-09-03 21:26:40

标签: c# asp.net-mvc json serialization json.net

我已经实现了DefaultContractResolver来包含我想要序列化的某些属性。我可以使用以下代码提取出每个属性和Object.property(嵌套对象),但是,在尝试序列化时,它没有找到嵌套对象的property.property并且在转换时失败。

public class DynamicContractResolver : DefaultContractResolver
{
    private List<string> mPropertiesToSerialize = null;

    public DynamicContractResolver(List<string> propertiesToSerialize)
    {
        this.mPropertiesToSerialize = propertiesToSerialize;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> objProperties = new List<JsonProperty>();
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

        objProperties = properties.Where(p => mPropertiesToSerialize.Contains(p.PropertyName)).ToList();

        foreach (var jProperty in properties)
        {
            if (!jProperty.PropertyType.IsClass) 
                continue;

            var nestedObjProperties = base.CreateProperties(jProperty.PropertyType, memberSerialization);
            foreach (var nestedjProperty in nestedObjProperties)
            {
                if (objProperties.Any(nj => (nj.PropertyName == nestedjProperty.PropertyName)))
                    continue;

                if (mPropertiesToSerialize.Contains(nestedjProperty.PropertyName))
                {
                    objProperties.Add(nestedjProperty);
                }
            }
        }
        return objProperties;
    }
}

失败的用法:

var contractResolver = new DynamicContractResolver(propertiesToSerialize);          
var serializedObj =
JsonConvert.SerializeObject(contact, Formatting.None,
                new JsonSerializerSettings { ContractResolver = contractResolver });

使用上面,我可以让它迭代Contact对象的所有属性,但是在序列化时,它似乎没有深入到像这里的Account这样的嵌入对象,并抛出错误,找不到属性。由于我使用的是JsonProperty列表,我希望我添加到要序列化的列表中的对象具有足够的序列化信息,以便从嵌套对象中提取适当的属性。显然这只有1级深度,但这不是手头的问题。

为什么不向下钻取到嵌套对象并从Contact中提取它的属性值?

public class Contact
{
    public string Name{ get; set; }
    public Account Account { get; set; }
}
public class Account 
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string EmailAddress { get; set; }
}

1 个答案:

答案 0 :(得分:0)

找到解决此问题的方法。

我没有覆盖createProperties,而是通过重写不需要的CreateProperty(JsonProperty CreateProperty(MemberInfo成员,MemberSerialization memberSerialization))来为每个属性设置property.ShouldSerialize为false,并且只返回那些需要的东西!