Skip to content

Instantly share code, notes, and snippets.

@winnicki
Created September 2, 2017 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save winnicki/0937e2539be3a4d535226d4e19d0fd46 to your computer and use it in GitHub Desktop.
Save winnicki/0937e2539be3a4d535226d4e19d0fd46 to your computer and use it in GitHub Desktop.
DynamicContractResolver
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace JsonPerf.Resolvers
{
/// <summary>
/// Can be used for any type to dynamically specify which properties are part of the serialization contract
/// </summary>
public class DynamicContractResolver : DefaultContractResolver
{
readonly List<string> _contractProperties;
IList<JsonProperty> _jsonProperties;
public DynamicContractResolver(params string[] contractProperties)
{
_contractProperties = contractProperties?.ToList();
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
if (_contractProperties == null || !_contractProperties.Any())
return properties;
// only serialize our dynamic contract properties
_jsonProperties =
properties
.Join(
_contractProperties,
jsonProperty => jsonProperty.PropertyName,
typeProperty => typeProperty,
(jsonProperty, arg2) => jsonProperty)
.ToList();
return _jsonProperties;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment