How to exclude specific type from json serialization

 ̄綄美尐妖づ 提交于 2019-12-22 07:08:11

问题


I am logging all requests to my WCF web services, including the arguments, to the database. This is the way I do it:

  • create a class WcfMethodEntry which derives from PostSharp's aspect OnMethodBoundaryAspect,
  • annotate all WCF methods with WcfMethodEntry attribute,
  • in the WcfMethodEntry I serialize the method arguments to json with the JsonConvert.SerializeObject method and save it to the database.

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?

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"
            }
         ]
      }
   }
]

Desired output:

[
   {
      "SaveCommand":{
         "Id":5,
         "PersonalData":{
            "GenderId":2,
            "NationalityCode":"DEU",
            "FirstName":"John",
            "LastName":"Doe",
         },
         "BiometricAttachments":[
            {
               "BiometricAttachmentTypeId":1,
               "Parameters":null,
               "Content":"..."
            }
         ]
      }
   }
]

Edit: I can't change the classes that are used as arguments for web service methods - that also means that I cannot use JsonIgnore attribute.


回答1:


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:

Reducing Serialized JSON Size




回答2:


You could just use [JsonIgnore] for this specific property.

[JsonIgnore]
public Byte[] ByteArray { get; set; }

Otherwise you can also try this: Exclude property from serialization via custom attribute (json.net)




回答3:


Try to use the JsonIgnore attribute.



来源:https://stackoverflow.com/questions/33258314/how-to-exclude-specific-type-from-json-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!