sve*_*vit 5 .net c# wcf postsharp json.net
我正在将对WCF Web服务的所有请求(包括参数)记录到数据库中.这就是我这样做的方式:
这工作正常,但有时参数非常大,例如一个自定义类,带有几个带有照片,指纹的字节数组等.我想从序列化中排除所有这些字节数组数据类型,这将是最好的方法做到了吗?
序列化json的示例:
[
{
"SaveCommand":{
"Id":5,
"PersonalData":{
"GenderId":2,
"NationalityCode":"DEU",
"FirstName":"John",
"LastName":"Doe",
},
"BiometricAttachments":[
{
"BiometricAttachmentTypeId":1,
"Parameters":null,
"Content":"large Base64 encoded string"
}
]
}
}
]
Run Code Online (Sandbox Code Playgroud)
期望的输出:
[
{
"SaveCommand":{
"Id":5,
"PersonalData":{
"GenderId":2,
"NationalityCode":"DEU",
"FirstName":"John",
"LastName":"Doe",
},
"BiometricAttachments":[
{
"BiometricAttachmentTypeId":1,
"Parameters":null,
"Content":"..."
}
]
}
}
]
Run Code Online (Sandbox Code Playgroud)
编辑:我不能更改用作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;
}
}
Run Code Online (Sandbox Code Playgroud)
用法和样品:
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[])) });
Run Code Online (Sandbox Code Playgroud)
输出:
{
"Name": "Test"
}
Run Code Online (Sandbox Code Playgroud)
更多信息可以在这里找到: