小写的自定义Json.NET合同解析器下划线到驼峰 [英] Custom Json.NET contract resolver for lowercase underscore to CamelCase

查看:798
本文介绍了小写的自定义Json.NET合同解析器下划线到驼峰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作在ASP.NET MVC一个REST API,其中所产生的序列化的JSON使用lowercase_underscore的属性。

从类与字符串属性,我得到JSON如下:

  {
  FIRST_NAME:查理
  姓:布朗
}

注意lowercase_underscore名称。

我用它来为我这样做自动转换合同解析器:

公共类JsonLowerCaseUnderscoreContractResolver:DefaultContractResolver
{
    私人正则表达式的regex ​​=新的正则表达式(((^ [A-Z]))([A-Z])?!);    保护覆盖字符串ResolvePropertyName(字符串propertyName的)
    {
        返回regex.Replace(propertyName的,_ $ 2)ToLower将()。
    }
}

这一切工作正常,但我不知道如何来实现与Json.NET相反。因此,例如,我可以声明如下API方法,并且知道传入的JSON的请求体转换为适当的对象:

将公共对象(INT ID,[FromBody]人的人)


解决方案

OK,找到了解决办法。我错过了类默认构造函数。一旦我这样做,映射调用方法时工作。其实,我也可以删除FromBody说明:

将公共对象(INT ID,人的人)

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)

这篇关于小写的自定义Json.NET合同解析器下划线到驼峰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆