我已经实现了DefaultContractResolver,以包括我想要序列化的某些属性。我可以使用以下代码提取每个属性和Object.properties(嵌套对象),但是,在尝试序列化时,它找不到嵌套对象的property.properties,转换失败。
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列表,所以我希望添加到要序列化的列表中的对象有足够的信息进行序列化,以便从嵌套对象中提取适当的属性。显然,这只深入了一个层次,但这不是眼前的问题。
为什么它不深入到嵌套对象并从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; }
}
找到了解决这个问题的方法。
我最终没有覆盖createProperties,而是设置了property。通过重写不需要的CreateProperty(JsonProperty CreateProperty(MemberInfo成员,MemberSerialization-MemberSerialization))并只返回所需的属性,应将每个属性的Serialize设置为false!