Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Json.NET contract resolver for lowercase underscore to CamelCase

I'm working on a REST API in ASP.NET MVC where the resulting serialised JSON uses lowercase_underscore for attributes.

From a class Person with string properties FirstName and Surname, I get JSON as follows:

{
  first_name: "Charlie",
  surname: "Brown"
}

Note the lowercase_underscore names.

The contract resolver I use to do this conversion automatically for me is:

public class JsonLowerCaseUnderscoreContractResolver : DefaultContractResolver
{
    private Regex regex = new Regex("(?!(^[A-Z]))([A-Z])");

    protected override string ResolvePropertyName(string propertyName)
    {
        return regex.Replace(propertyName, "_$2").ToLower();
    }
}

This all works fine, but I don't know how to implement the reverse with Json.NET. So that, for example, I can declare an API method as follows, and it knows to convert incoming JSON in the request body to the appropriate object:

public object Put(int id, [FromBody] Person person)
like image 954
Diego Barros Avatar asked Aug 05 '13 05:08

Diego Barros


1 Answers

OK, found the solution. I was missing a default constructor for the Person class. Once I did that, the mapping worked when calling the Put method. In fact, I could also remove the FromBody specifier:

public object Put(int id, Person person)
like image 115
Diego Barros Avatar answered Oct 28 '22 16:10

Diego Barros