我正在将对我的 WCF Web 服务的所有请求(包括参数)记录到数据库中。这是我的做法:
- 创建一个派生自 PostSharp 方面 OnMethodBoundaryAspect 的类 WcfMethodEntry,
- 使用 WcfMethodEntry 属性注释所有 WCF 方法,
- 在 WcfMethodEntry 中,我使用 JsonConvert.SerializeObject 方法将方法参数序列化为 json,并将其保存到数据库中。
这工作正常,但有时参数非常大,例如带有几个字节数组的自定义类,照片,指纹等。我想从序列化中排除所有这些字节数组数据类型,那会是什么最好的方法是什么?
序列化 json 示例:
[
{
"SaveCommand":{
"Id":5,
"PersonalData":{
"GenderId":2,
"NationalityCode":"DEU",
"FirstName":"John",
"LastName":"Doe",
},
"BiometricAttachments":[
{
"BiometricAttachmentTypeId":1,
"Parameters":null,
"Content":"large Base64 encoded string"
}
]
}
}
]
期望的输出:
[
{
"SaveCommand":{
"Id":5,
"PersonalData":{
"GenderId":2,
"NationalityCode":"DEU",
"FirstName":"John",
"LastName":"Doe",
},
"BiometricAttachments":[
{
"BiometricAttachmentTypeId":1,
"Parameters":null,
"Content":"..."
}
]
}
}
]
编辑:我无法更改用作 Web 服务方法参数的类 - 这也意味着我无法使用 JsonIgnore 属性。
最佳答案
以下内容允许您排除要从生成的 json 中排除的特定数据类型。它的使用和实现非常简单,并且改编自底部的链接。
你可以使用它,因为你不能改变实际的类:
public class DynamicContractResolver : DefaultContractResolver
{
private Type _typeToIgnore;
public DynamicContractResolver(Type typeToIgnore)
{
_typeToIgnore = typeToIgnore;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
properties = properties.Where(p => p.PropertyType != _typeToIgnore).ToList();
return properties;
}
}
用法和示例:
public class MyClass
{
public string Name { get; set; }
public byte[] MyBytes1 { get; set; }
public byte[] MyBytes2 { get; set; }
}
MyClass m = new MyClass
{
Name = "Test",
MyBytes1 = System.Text.Encoding.Default.GetBytes("Test1"),
MyBytes2 = System.Text.Encoding.Default.GetBytes("Test2")
};
JsonConvert.SerializeObject(m, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver(typeof(byte[])) });
输出:
{
"Name": "Test"
}
更多信息可以在这里找到:
关于c# - 如何从 json 序列化中排除特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33258314/