Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[QUESTION]首字母为单个字母的驼峰转换问题 #607

Closed
gsmoking opened this issue Aug 3, 2022 · 4 comments
Closed

[QUESTION]首字母为单个字母的驼峰转换问题 #607

gsmoking opened this issue Aug 3, 2022 · 4 comments
Labels
fixed question Further information is requested
Milestone

Comments

@gsmoking
Copy link

gsmoking commented Aug 3, 2022

@Data
public class TestVo(){
   
   //JSON.toJSONString()会转换为PName
   private String pName;
    //JSON.toJSONString()转化正常
  private String proName;

 
}

public void testJSONToString(){
   TestVo testVo = new TestVo();
    testVo.setPName("test");
    testVo.setProName("test1");
    System.out.println(JSON.toJSONString(vo));
   //期望输出: {"pName":"test", "proName":"test1"}
  //实际输出:  {"PName":"test", "proName":"test1"}
}

问题补充:

  1. 使用lomok时,set方法为setPName(), 转换异常
  2. 正常生成的set方法为setpName(),能够正常转换
  3. 使用兼容版本的JSON.toJSONString(),两种方式都能正常转换
@gsmoking gsmoking added the question Further information is requested label Aug 3, 2022
@subenkun
Copy link

subenkun commented Aug 9, 2022

20220809172926
20220809172939
同样的问题

@wenshao
Copy link
Member

wenshao commented Aug 28, 2022

现在的实现是参考java.beans.Introspector#decapitalize方法:

package java.beans;

public class Introspector {
    public static String decapitalize(String name) {
        if (name == null || name.length() == 0) {
            return name;
        }
        if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
                        Character.isUpperCase(name.charAt(0))){
            return name;
        }
        char chars[] = name.toCharArray();
        chars[0] = Character.toLowerCase(chars[0]);
        return new String(chars);
    }

}

fastjson 1.x的实现,一直有人反馈说不对,希望和java.beans.Introspector#decapitalize方法一致,为了保证兼容一直没改。现在是2.0就改了。

下面分别是fastjson2、jackson、fastjson1、gson的结果,各不相同,如下:

// fastjson2
{"PName":"test"}

// jackson
{"pname":"test"}

// fastjson1 & gson
{"pName":"test"}

你可以通过配置JSONField输出你要的,或者你用最新版本的2.0.13-SNAPSHOT版本,然后把field声明为public,比如:

 @Data
public class Bean1 {
        public String pName;
}

@wenshao wenshao added this to the 2.0.13 milestone Aug 28, 2022
@wenshao wenshao added the fixed label Aug 28, 2022
@wenshao
Copy link
Member

wenshao commented Sep 10, 2022

https://github.com/alibaba/fastjson2/releases/tag/2.0.13
2.0.13版本已经发布,请用帮忙用新版本验证

@wenshao wenshao closed this as completed Sep 10, 2022
@zhrgithub
Copy link

zhrgithub commented Sep 10, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fixed question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants