How to exclude specific type from json serialization
Asked Answered
B

4

5

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.

Borne answered 21/10, 2015 at 11:36 Comment(4)
Is it possible to edit your c# object before serialization?Broker
@Broker hmm... I don't know, you mean that I could add JsonIgnore attribute to the object with the help of reflection? Or just clear those properties? Probably...Borne
@Borne - [JsonIgnore] would solve it.Atahualpa
@Borne I thought about property clearing but JsonIgnore look like better solution :)Broker
A
12

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

Atahualpa answered 21/10, 2015 at 12:17 Comment(1)
ha! glad to helpAtahualpa
C
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)

Clearance answered 21/10, 2015 at 11:48 Comment(1)
I cannot use JsonIgnore attribute, please see my edit. I will check your link, thanks.Borne
S
1

Another way would be to use a custom type converter and have it return null, so the property is there but it will simply be null.

For example i use this so i can serialize Exceptions:

/// <summary>
/// Exception have a TargetSite property which is a methodBase.
/// This is useless to serialize, and can cause huge strings and circular references - so this converter always returns null on that part.
/// </summary>
public class MethodBaseConverter : JsonConverter<MethodBase?>
{
    public override void WriteJson(JsonWriter writer, MethodBase? value, JsonSerializer serializer)
    {
        // We always return null so we don't object cycle.
        serializer.Serialize(writer, null);
    }

    public override MethodBase? ReadJson(JsonReader reader, Type objectType, MethodBase? existingValue, bool hasExistingValue,
        JsonSerializer serializer)
    {
        return null;
    }
}
Schist answered 30/8, 2022 at 8:18 Comment(0)
L
-1

Try to use the JsonIgnore attribute.

Lilialiliaceous answered 21/10, 2015 at 11:50 Comment(1)
I cannot use JsonIgnore attribute, please see my edit.Borne

© 2022 - 2024 — McMap. All rights reserved.