Custom Json.NET contract resolver for lowercase underscore to CamelCase

主宰稳场 提交于 2019-12-09 15:12:21

问题


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)

回答1:


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)


来源:https://stackoverflow.com/questions/18051395/custom-json-net-contract-resolver-for-lowercase-underscore-to-camelcase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!