我正在尝试使用 newtonsoft.json 序列化模型图,我知道使用ignore属性或使用自定义ContractResolver我可以忽略序列化的特定属性吗?
这是我用来忽略属性的自定义ContractResolver:
public class PropertyIgnoreSerializerContractResolver : DefaultContractResolver
{
private readonly Dictionary<Type, HashSet<string>> _ignores;
public PropertyIgnoreSerializerContractResolver()
{
_ignores = new Dictionary<Type, HashSet<string>>();
}
public void IgnoreProperty(Type type, params string[] jsonPropertyNames)
{
if (!_ignores.ContainsKey(type))
_ignores[type] = new HashSet<string>();
foreach (var prop in jsonPropertyNames)
_ignores[type].Add(prop);
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (IsIgnored(property.DeclaringType, property.PropertyName))
property.ShouldSerialize = i => false;
return property;
}
private bool IsIgnored(Type type, string jsonPropertyName)
{
if (!_ignores.ContainsKey(type))
return false;
return _ignores[type].Contains(jsonPropertyName);
}
}
但在我的情况下,我需要在图模型中包含要序列化的特定属性,而不是在该图中排除很多属性?
有没有办法将其配置为序列化特定属性?
答案 0 :(得分:1)
我已经修改了 PropertyIgnoreSerializerContractResolver 以反转逻辑以包含属性而不是忽略它们。
首先想象我们有这些课程:
<p>
<input type="checkbox" name="cat1" value="ON">Art1
<input type="checkbox" name="cat1" value="ON">Art2
<input type="checkbox" name="cat1" value="ON">Art3
<input type="checkbox" name="cat1" value="ON">Art4
</p>
<p><button type="button" onClick="checkIsChecked()">Check Options</button></p>
序列化类和我的自定义ContractResolver以包含要序列化的属性,它们如下所示:
function checkIsChecked(){
var inputs = document.getElementsByTagName('input');
var flag = false;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].checked) {
flag = true;
}
}
if(!flag){
alert("Please check at least one ");
return false;
}
}
Inside Main方法:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public Person Teacher { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? BOD { get; set; }
public decimal Salary { get; set; }
}
所以这里 PropertyIncludeSerializerContractResolver 会忽略所有未指定序列化的引用类型。
我希望我的代码可以帮助他人。