我的目标是序列化不具备任何具有特定自定义属性的属性和属性的属性。
以下课程:
main()
当我调用方法public class Msg
{
public long Id { get; set; }
[CustomAttributeA]
public string Text { get; set; }
[CustomAttributeB]
public string Status { get; set; }
}
时,我希望得到以下输出:
Serialize(object, CustomAttributeA)
当我致电{
"Id" : someId,
"Text" : "some text"
}
时,我希望有以下内容:
Serialize(object, CustomAttributeB)
我已经读过可以通过创建自定义{
"Id" : someId,
"Status" : "some status"
}
来实现此目的,但在这种情况下我必须创建两个单独的合同解析器吗?
答案 0 :(得分:4)
您不需要两个单独的解析器来实现您的目标。只需将自定义ContractResolver
设为通用,其中type参数表示序列化时要查找的属性。
例如:
public class CustomResolver<T> : DefaultContractResolver where T : Attribute
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
foreach (JsonProperty prop in list)
{
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null)
{
// if the property has any attribute other than
// the specific one we are seeking, don't serialize it
if (pi.GetCustomAttributes().Any() &&
pi.GetCustomAttribute<T>() == null)
{
prop.ShouldSerialize = obj => false;
}
}
}
return list;
}
}
然后,您可以创建一个辅助方法来创建解析器并序列化您的对象:
public static string Serialize<T>(object obj) where T : Attribute
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new CustomResolver<T>(),
Formatting = Formatting.Indented
};
return JsonConvert.SerializeObject(obj, settings);
}
如果要序列化,请按以下方式调用帮助程序:
string json = Serialize<CustomAttributeA>(msg);