fastjson 序列化驼峰问题

dzhpxtsq  于 10个月前  发布在  其他
关注(0)|答案(1)|浏览(103)

由于特殊原因我设置了全局PropertyNamingStrategy.SnakeCase,但有些类需要单独设置驼峰序列化PropertyNamingStrategy.CamelCase,于是在类上加了@jsontype(naming = PropertyNamingStrategy.CamelCase),但不起作用。
com.alibaba fastjson 1.2.75

bbuxkriu

bbuxkriu1#

复现代码如下:

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.PropertyNamingStrategy;
  3. import com.alibaba.fastjson.annotation.JSONType;
  4. import com.alibaba.fastjson.serializer.SerializeConfig;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import org.junit.Test;
  8. public class Issue3652 {
  9. @Test
  10. public void test_SerializeConfig_different_Class_Annotation() {
  11. Object[] models = new Object[]{
  12. new Model1("hello,world"),
  13. new Model2("hello,world"),
  14. new Model3("hello,world"),
  15. new Model4("hello,world"),
  16. };
  17. for (int i = 0; i < 4; i++) {
  18. System.out.printf("---------- begin circle %d%n", i);
  19. for (int j = 0; j < 4; j++) {
  20. SerializeConfig config = new SerializeConfig();
  21. config.propertyNamingStrategy = PropertyNamingStrategy.values()[j];
  22. System.out.println(JSON.toJSONString(models[i], config));
  23. }
  24. System.out.printf("---------- end circle %d%n", i);
  25. }
  26. }
  27. @JSONType(naming = PropertyNamingStrategy.CamelCase)
  28. @Data
  29. @AllArgsConstructor
  30. public class Model1 {
  31. private String goodBoy;
  32. }
  33. @JSONType(naming = PropertyNamingStrategy.PascalCase)
  34. @Data
  35. @AllArgsConstructor
  36. public class Model2 {
  37. private String goodBoy;
  38. }
  39. @JSONType(naming = PropertyNamingStrategy.SnakeCase)
  40. @Data
  41. @AllArgsConstructor
  42. public class Model3 {
  43. private String goodBoy;
  44. }
  45. @JSONType(naming = PropertyNamingStrategy.KebabCase)
  46. @Data
  47. @AllArgsConstructor
  48. public class Model4 {
  49. private String goodBoy;
  50. }
  51. }

输出为

  1. ---------- begin circle 0
  2. {"goodBoy":"hello,world"}
  3. {"GoodBoy":"hello,world"}
  4. {"good_boy":"hello,world"}
  5. {"good-boy":"hello,world"}
  6. ---------- end circle 0
  7. ---------- begin circle 1
  8. {"GoodBoy":"hello,world"}
  9. {"GoodBoy":"hello,world"}
  10. {"GoodBoy":"hello,world"}
  11. {"GoodBoy":"hello,world"}
  12. ---------- end circle 1
  13. ---------- begin circle 2
  14. {"good_boy":"hello,world"}
  15. {"good_boy":"hello,world"}
  16. {"good_boy":"hello,world"}
  17. {"good_boy":"hello,world"}
  18. ---------- end circle 2
  19. ---------- begin circle 3
  20. {"good-boy":"hello,world"}
  21. {"good-boy":"hello,world"}
  22. {"good-boy":"hello,world"}
  23. {"good-boy":"hello,world"}
  24. ---------- end circle 3

当类注解为 PropertyNamingStrategy.CamelCase 时,注解是无效的,会按照config输出.
原因就是上图红框框出来的那个判断.

如图,JSONType的默认naming为 PropertyNamingStrategy.CamelCase , 所以才需要框内的判断去避免"没有声明naming却使用了CamelCase"的情况.

展开查看全部

相关问题