Skip to content

Instantly share code, notes, and snippets.

@lorddev
Last active August 29, 2015 13:57
Show Gist options
  • Save lorddev/9439561 to your computer and use it in GitHub Desktop.
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...
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