是否可以为JsonConvert.PopulateObject定义选项以排除目标对象的接口实现中不存在的json中给出的字段?
public interface IElementWriter
{
string Name { get; set; }
}
public interface IElementUpdateWriter : IElementWriter
{
string FirstName { get; set; }
}
public interface IElementInsertWriter : IElementWriter
{
DateTime? CreationDate { get; set; }
}
public class Element:IElementWriter, IElementInsertWriter, IElementUpdateWriter {
public int ID { get; set; }
public string Name { get; set; }
public DateTime? CreationDate { get; set; }
public string FirstName { get; set; }
}
static void Main(string[] args)
{
IElementWriter element = new Element() { ID = 1, Name = "SourceName", CreationDate=DateTime.Today, FirstName="SourceFirstName" };
string json = "{ id:'8', Name:'newName', FirstName:'newFirstName' }";
JsonConvert.PopulateObject(json, element, new JsonSerializerSettings() {
});
Console.WriteLine(JsonConvert.SerializeObject(element));
Console.ReadLine();
}
结果:
{“ ID”:8,“名称”:“ newName”,“ CreationDate”:“ 2019-06-05T00:00:00 + 02:00”,“名字”:“ newFirstName”}
必需,因为IElementWriter没有ID或FirstName:
{“ ID”:1,“名称”:“ newName”,“ CreationDate”:“ 2019-06-05T00:00:00 + 02:00”,“名字”:“ SourceFirstName”}
答案 0 :(得分:0)
JsonSerializerSettings
中没有简单的设置会导致JsonConvert.PopulateObject()
填充派生类型的实例,就好像它是某个基本类型的实例一样。要确认这一点,您可以检查JsonSerializerInternalReader.Populate()
的来源,该来源仅将reader
和target
作为参数,并直接从其类型中提取目标的contract:
public void Populate(JsonReader reader, object target)
{
Type objectType = target.GetType();
JsonContract contract = Serializer._contractResolver.ResolveContract(objectType);
因此,您的选择包括:
修改Element
类的定义,并将[JsonIgnore]
添加到您不想填充的属性中。
您可能不想这样做,因为它将阻止属性被序列化或反序列化。
使用custom contract resolver忽略Element
的所有属性,这些属性也不是IElementWriter
的属性。
这似乎是更好的解决方案。
假设您选择选项#2,则可以引入以下自定义合同解析器:
public class UpcastingContractResolver<TDerived, TBase> : DefaultContractResolver where TDerived: TBase
{
readonly HashSet<string> baseProperties = ((JsonObjectContract)JsonSerializer.Create().ContractResolver.ResolveContract(typeof(TBase)))
.Properties.Select(p => p.UnderlyingName)
.ToHashSet();
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
if (type == typeof(TDerived) || type.IsSubclassOf(typeof(TDerived)))
{
foreach (var property in properties)
{
if (!baseProperties.Contains(property.UnderlyingName))
property.Ignored = true;
}
}
return properties;
}
}
然后,将实例缓存为suggested by Newtonsoft以提高性能:
static IContractResolver elementAsElementWriterResolver = new UpcastingContractResolver<Element, IElementWriter>();
并按照以下步骤填充您的element
:
// Only populate those properties present in IElementWriter
JsonConvert.PopulateObject(json, element, new JsonSerializerSettings
{
ContractResolver = elementAsElementWriterResolver
});
演示小提琴here。