sventevit
sventevit

Reputation: 4816

How to exclude specific type from json serialization

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

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.

Upvotes: 5

Views: 3599

Answers (4)

sommmen
sommmen

Reputation: 7628

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;
    }
}

Upvotes: 1

winsky
winsky

Reputation: 19

Try to use the JsonIgnore attribute.

Upvotes: -1

Ric
Ric

Reputation: 13248

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

Upvotes: 12

Camo
Camo

Reputation: 1180

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)

Upvotes: 2

Related Questions