Created
October 24, 2014 10:22
-
-
Save JohanLarsson/a480f09240da5c0401e5 to your computer and use it in GitHub Desktop.
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
using Newtonsoft.Json; | |
using NUnit.Framework; | |
public class Demo | |
{ | |
private JsonSerializerSettings _settings; | |
[SetUp] | |
public void SetUp() | |
{ | |
_settings = new JsonSerializerSettings() | |
{ | |
ContractResolver = new SnakeCaseContractResolver() | |
}; | |
} | |
[Test] | |
public void Deserilaize() | |
{ | |
var json = "{\"first_name\":\"Johan\"}"; | |
var dto = JsonConvert.DeserializeObject<Dto>(json, _settings); | |
} | |
[Test] | |
public void Serialize() | |
{ | |
var dto = new Dto("Johan"); | |
var json = JsonConvert.SerializeObject(dto, _settings); | |
Assert.AreEqual("{\"first_name\":\"Johan\"}", json); | |
} | |
} |
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 Dto | |
{ | |
private Dto() | |
{ | |
} | |
public Dto(string firstName) | |
{ | |
FirstName = firstName; | |
} | |
public string FirstName { get; private set; } | |
} |
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
using System; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text.RegularExpressions; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
public class SnakeCaseContractResolver : DefaultContractResolver | |
{ | |
private readonly string[] _prefixable = { "name" }; | |
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) | |
{ | |
JsonProperty prop = base.CreateProperty(member, memberSerialization); | |
string propertyName = prop.PropertyName; | |
if (_prefixable.Any(x => this.TryPrefix(propertyName, x, out propertyName))) | |
{ | |
prop.PropertyName = propertyName; | |
} | |
prop.PropertyName = propertyName.ToLower(); | |
return prop; | |
} | |
private bool TryPrefix(string input, string prefix, out string prefixed) | |
{ | |
if (input.IndexOf(prefix, StringComparison.OrdinalIgnoreCase) > 0) | |
{ | |
prefixed = Regex.Replace(input, prefix, string.Concat("_", prefix.ToLower()), RegexOptions.IgnoreCase); | |
return true; | |
} | |
prefixed = input; | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment