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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With