其他分享
首页 > 其他分享> > 我可以使用Camelcase转换属性(如ID(两个大写字母))得到什么

我可以使用Camelcase转换属性(如ID(两个大写字母))得到什么

作者:互联网

我有一个像这样的课程:

public class MyClass{
    public int ID {get;set;}
    public string CName{get;set}
    public string FirstName{get;set}        
}

当我使用newtonsoft camelcase将此类转换为json时,我得到了类似的内容

{
  id:1,
  cname:xxx,
  fistName:xxx
}

为什么不将ID转换为iD,将CName转换为cName?骆驼的确切规则是什么?

{
  iD:1,
  cName:xxx,
  fistName:xxx
}

解决方法:

camelcase的第一个单词都是小写.因此,ID变为id,而CName变为cname.之后,每个附加单词仅将首字母大写,因此名称变为Name.也就是说,Newtonsoft将ID和CName视为单个单词,而不是多个单词.

这是在Newtonsoft中将字符转换为驼峰字母的方法.如您所见,它几乎没有逻辑将字符串解析为单个单词.该代码仅假定大写的第一个单词在第二个字母之后的(1)和在找到空格或大写字母后跟小写字母的(2)之后结束.

    public static string ToCamelCase(string s)
    {
        if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0]))
        {
            return s;
        }

        char[] chars = s.ToCharArray();

        for (int i = 0; i < chars.Length; i++)
        {
            if (i == 1 && !char.IsUpper(chars[i]))
            {
                break;
            }

            bool hasNext = (i + 1 < chars.Length);
            if (i > 0 && hasNext && !char.IsUpper(chars[i + 1]))
            {
                // if the next character is a space, which is not considered uppercase 
                // (otherwise we wouldn't be here...)
                // we want to ensure that the following:
                // 'FOO bar' is rewritten as 'foo bar', and not as 'foO bar'
                // The code was written in such a way that the first word in uppercase
                // ends when if finds an uppercase letter followed by a lowercase letter.
                // now a ' ' (space, (char)32) is considered not upper
                // but in that case we still want our current character to become lowercase
                if (char.IsSeparator(chars[i + 1]))
                {
                    chars[i] = ToLower(chars[i]);
                }

                break;
            }

            chars[i] = ToLower(chars[i]);
        }

        return new string(chars);
    }

标签:camelcasing,json-net,c
来源: https://codeday.me/bug/20191025/1926491.html