Created
December 10, 2014 22:23
-
-
Save mburbea/32de810859a7be2fd25f to your computer and use it in GitHub Desktop.
SpecifiedConverterContractResolver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SpecifiedConverterContractResolver : DefaultContractResolver | |
{ | |
readonly List<JsonConverter> _converters; | |
readonly bool _camelCaseProperties; | |
public SpecifiedConverterContractResolver(bool camelCaseProperties, IEnumerable<JsonConverter> converters) | |
{ | |
if (converters == null) | |
{ | |
throw new ArgumentNullException("converters"); | |
} | |
_camelCaseProperties = camelCaseProperties; | |
_converters = new List<JsonConverter>(); | |
foreach(var converter in converters) | |
{ | |
if (converter == null) throw new ArgumentNullException("converters"); | |
_converters.Add(converter); | |
} | |
if(_converters.Count==0) | |
{ | |
throw new ArgumentException("Need to specify at least one converter", "converters"); | |
} | |
} | |
public SpecifiedConverterContractResolver(bool camelCaseProperties, params JsonConverter[] converters): this(camelCaseProperties, converters as IEnumerable<JsonConverter>) | |
{ | |
} | |
protected override string ResolvePropertyName(string propertyName) | |
{ | |
return _camelCaseProperties ? StringUtils.ToCamelCase(propertyName) : propertyName; | |
} | |
protected override JsonContract CreateContract(Type objectType) | |
{ | |
JsonContract contract = base.CreateContract(objectType); | |
contract.Converter = _converters.FirstOrDefault(converter => converter.CanConvert(objectType)); | |
return contract; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment