Last active
August 29, 2015 13:57
-
-
Save lorddev/9439561 to your computer and use it in GitHub Desktop.
Say you're trying to serialize a JSON API such as Google Maps where all the properties are lowercase and words are separated by underscores. But in order to keep your own code clean, you need to use camel casing...
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.Text.RegularExpressions; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
namespace Test | |
{ | |
public class FooTest | |
{ | |
public void TestCustomResolver() | |
{ | |
var settings = new JsonSerializerSettings | |
{ | |
ContractResolver = | |
new UnderscoreContractResolver() | |
}; | |
var bob = new { PropertyName = "asdf" }; | |
string json = JsonConvert.SerializeObject(bob, Formatting.Indented, settings); | |
Assert.AreEqual("{\r\n \"property_name\": \"asdf\"\r\n}", json); | |
} | |
} | |
public class UnderscoreContractResolver : DefaultContractResolver | |
{ | |
protected override string ResolvePropertyName(string propertyName) | |
{ | |
return Regex.Replace(propertyName, "(?<=[a-z])[A-Z]", m => "_" + m).ToLower(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment