如何排除JSON序列化特定类型 [英] How to exclude specific type from json serialization
问题描述
我记录所有请求我的WCF web服务,其中包括的参数,到数据库中。这是我做的方式:
I am logging all requests to my WCF web services, including the arguments, to the database. This is the way I do it:
- 创建一个类WcfMethodEntry从PostSharp的方面OnMethodBoundaryAspect,
- 注释所有WCF方法与WcfMethodEntry属性,
- 在WcfMethodEntry序列化的方法参数JSON与JsonConvert.SerializeObject方法,并将其保存到数据库中。
派生
这工作正常,但有时参数是相当大的,例如一对夫妇有照片,指纹等字节数组,我想自定义类?排除系列化所有的字节数组数据类型,这将是做到这一点的最好办法
This works ok, but sometimes the arguments are quite large, for example a custom class with a couple of byte arrays with photo, fingerprint etc. I would like to exclude all those byte array data types from serialization, what would be the best way to do it?
序列化的JSON的示例:
Example of a serialized 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属性
I can't change the classes that are used as arguments for web service methods - that also means that I cannot use JsonIgnore attribute.
推荐答案
下面,您可以排除要从生成的JSON排除特定的数据类型。它的使用和实施很简单,从底部的链接被改编
The following allows you to exclude a specific data-type that you want excluded from the resulting json. It's quite simple to use and implement and was adapted from the link at the bottom.
您可以使用它作为你不能改变实际的类:
You can use this as you cant alter the actual classes:
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;
}
}
用法示例:
Usage and sample:
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[])) });
输出:
Output:
{
"Name": "Test"
}
更多信息可以在这里找到:
More information can be found here:
这篇关于如何排除JSON序列化特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!