当前位置:   article > 正文

FastJSON解析-----@JSONField注解详解_jsonfield alternatenames

jsonfield alternatenames

一、依赖

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.21</version>
  5. </dependency>

二、FastJson序列化方式  

    PS:这里只陈述第一种方式。

  • 通过@JSONField定制序列化-----配置在字段或者getter/setter方法上。
  • 通过@JSONType定制序列化-----配置在类上
  • 通过SerializeFilter定制序列化 
  • 通过ParseProcess定制反序列化

三、@JSONField

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})//一般作用在字段上
  3. public @interface JSONField {
  4. int ordinal() default 0;//配置序列化和反序列化的顺序
  5. String name() default "";//配置序列化和反序列化时字段的名字
  6. String format() default "";//字段格式化,对日期很有用
  7. boolean serialize() default true;//是否序列化
  8. boolean deserialize() default true;//是否反序列化
  9. SerializerFeature[] serialzeFeatures() default {};//控制序列化的一些规则,如NULL的处理
  10. Feature[] parseFeatures() default {};//控制反序列化的一些规则
  11. String label() default "";
  12. boolean jsonDirect() default false;//当有一个字段是字符串类型,里面是json格式数据,希望直接输入,而不是经过转义之后再输出。
  13. Class<?> serializeUsing() default Void.class;//对某一个类的某个属性定制序列化
  14. Class<?> deserializeUsing() default Void.class;//对某一个类的某个属性定制反序列化
  15. String[] alternateNames() default {};//反序列化时使用多个不同的字段名称
  16. }
  • ordinal
  1. @Data
  2. public class User {
  3. @JSONField(ordinal = 2)
  4. private String name;
  5. @JSONField(ordinal = 3)
  6. private String sex;
  7. @JSONField(ordinal = 1)
  8. private Integer age;
  9. }
  10. //序列化结果:顺序为age、name、sex
  11. {"age":20,"name":"zhangsan","sex":"男"}
  •  name
  1. @Data
  2. public class User {
  3. @JSONField(ordinal = 2 , name="userName")
  4. private String name;
  5. @JSONField(ordinal = 3)
  6. private String sex;
  7. @JSONField(ordinal = 1)
  8. private Integer age;
  9. }
  10. //序列化结果:name变为userName
  11. {"age":20,"userName":"zhangsan","sex":"男"}
  •  format
  1. @Data
  2. public class User {
  3. @JSONField(ordinal = 2 , name="userName")
  4. private String name;
  5. @JSONField(ordinal = 3 , format = "yyyy-MM-dd HH:mm:ss")
  6. private Date birthDay;
  7. @JSONField(ordinal = 1)
  8. private Integer age;
  9. }
  10. //序列化结果:
  11. {"age":20,"userName":"zhangsan","birthDay":"2018-11-05 18:26:46"}
  •  serialize

    默认情况下,是true,也就是所有字段都会被序列化。

  1. @Data
  2. public class User {
  3. @JSONField(ordinal = 2 , name="userName")
  4. private String name;
  5. @JSONField(ordinal = 3 , format = "yyyy-MM-dd HH:mm:ss")
  6. private Date birthDay;
  7. @JSONField(ordinal = 1 , serialize = false)
  8. private Integer age;
  9. }
  10. //序列化结果:age没有被序列化
  11. {"userName":"zhangsan","birthDay":"2018-11-05 18:29:19"}
  • deserialize
  1. @Data
  2. public class User {
  3. @JSONField(ordinal = 2 , name="userName")
  4. private String name;
  5. @JSONField(ordinal = 3 , format = "yyyy-MM-dd HH:mm:ss")
  6. private Date birthDay;
  7. @JSONField(ordinal = 1 , serialize = false)
  8. private Integer age;
  9. }
  10. @Test
  11. public void deserialize(){
  12. String str = "{\"age\":20,\"userName\":\"zhangsan\",\"birthDay\":\"2018-11-05 18:26:46\"}";
  13. User user = JSON.parseObject(str, User.class);
  14. System.out.println(user);
  15. }
  16. //反序列化结果:
  17. User(name=zhangsan, birthDay=Mon Nov 05 18:26:46 CST 2018, age=20)
  •  serialzeFreature

默认的序列化规则是当你的字段的值为null的时候,它是不会给你序列化这个字段的。我们可以通过serialzeFeatures的属性值SerializerFeature.WriteMapNullValue来控制,当属性的值为null时也输出该字段,字段的值为null。

  1. @Data
  2. public class User {
  3. @JSONField(ordinal = 2 , name="userName")
  4. private String name;
  5. @JSONField(ordinal = 3 , format = "yyyy-MM-dd HH:mm:ss" , serialzeFeatures = SerializerFeature.WriteMapNullValue)
  6. private Date birthDay;
  7. @JSONField(ordinal = 1 , serialize = false)
  8. private Integer age;
  9. }
  10. //JSON.toJSONString(user)序列化的结果:
  11. {"userName":"zhangsan","birthDay":null}
  12. //也可以如下使用,不在字段上做限制。这种情况针对所有字段。
  13. @Test
  14. public void test(){
  15. User user = initUser();
  16. String jsonStr = JSON.toJSONString(user , SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullNumberAsZero);
  17. System.out.println(jsonStr);
  18. }
  19. //输出结果:
  20. {"age":0,"userName":"zhangsan","birthDay":null}

 当然SerializerFeature类中还有很多其他的属性:

名称含义
QuoteFieldNames输出key时是否使用双引号,默认为true
UseSingleQuotes使用单引号而不是双引号,默认为false
WriteMapNullValue是否输出值为null的字段,默认为false
WriteEnumUsingToStringEnum输出name()或者original,默认为false
UseISO8601DateFormatDate使用ISO8601格式输出,默认为false
WriteNullListAsEmptyList字段如果为null,输出为[],而非null
WriteNullStringAsEmpty字符类型字段如果为null,输出为”“,而非null
WriteNullNumberAsZero数值字段如果为null,输出为0,而非null
  • parseFeatures 

    略............

  • jsonDirect
  1. @Data
  2. public class Group {
  3. private String name;
  4. @JSONField(jsonDirect = true)
  5. private String userDetail;
  6. }
  7. @Data
  8. public class User {
  9. @JSONField(ordinal = 2 , name="userName")
  10. private String name;
  11. @JSONField(ordinal = 3 , format = "yyyy-MM-dd HH:mm:ss")
  12. private Date birthDay;
  13. @JSONField(ordinal = 1 )
  14. private Integer age;
  15. }
  16. //测试
  17. @Test
  18. public void jsonDirect(){
  19. User user = new User();
  20. user.setName("zhangsan");
  21. user.setBirthDay(new Date());
  22. user.setAge(10);
  23. String userJSON = JSON.toJSONString(user);
  24. Group group = new Group();
  25. group.setName("1组");
  26. group.setUserDetail(userJSON);
  27. String grouJson = JSON.toJSONString(group);
  28. System.out.println(grouJson);
  29. }
  30. //输出结果:
  31. {"name":"1组","userDetail":{"birthDay":"2018-11-05 19:16:18","userName":"zhangsan","age":10}}
  32. //而不是:
  33. {"name":"1组","userDetail":"{\"age\":10,\"userName\":\"zhangsan\",\"birthDay\":\"2018-11-05 19:18:33\"}"}
  •  serializeUsing

    如果实体类某字段是String类型,但第三方的相同字段是Interger类型,那么,就需要我们传过去的JSON串中该字段作为key对应的值不可以带双引号。这种情况,也可以用此方法解决。

  1. //实体类
  2. @Data
  3. public class User {
  4. @JSONField(ordinal = 2 , name="userName")
  5. private String name;
  6. @JSONField(ordinal = 3 , format = "yyyy-MM-dd HH:mm:ss")
  7. private Date birthDay;
  8. @JSONField(ordinal = 1 , serializeUsing = ModelValueSerializer.class)
  9. private Integer age;
  10. }
  11. //工具类---需要实现ObjectSerializer重写write方法
  12. public class ModelValueSerializer implements ObjectSerializer {
  13. @Override
  14. public void write(JSONSerializer jsonSerializer, Object o, Object o1, Type type, int i) throws IOException {
  15. Integer value = (Integer) o;
  16. String text = value + "岁";
  17. jsonSerializer.write(text);
  18. }
  19. }
  20. //测试
  21. @Test
  22. public void test(){
  23. User user = new User();
  24. user.setName("zhangsan");
  25. user.setBirthDay(new Date());
  26. user.setAge(10);
  27. String jsonStr = JSON.toJSONString(user);
  28. System.out.println(jsonStr);
  29. }
  30. //结果:
  31. {"age":"10岁","userName":"zhangsan","birthDay":"2018-11-05 19:26:24"}
  • deserializeUsing

     略.........................

  • alternateNames
  1. @Data
  2. public class User {
  3. @JSONField(ordinal = 2 , name="userName" ,alternateNames = {"userName","studentName"})
  4. private String name;
  5. @JSONField(ordinal = 3 , format = "yyyy-MM-dd HH:mm:ss")
  6. private Date birthDay;
  7. @JSONField(ordinal = 1 , serializeUsing = ModelValueSerializer.class)
  8. private Integer age;
  9. }
  10. @Test
  11. public void alternateNames(){
  12. String jsonVal0 = "{\"age\":"10",\"name\":\"zhangsan\",\"birthDay\":\"2018-11-05 19:41:47\"}";
  13. String jsonVal1 = "{\"age\":11,\"userName\":\"lisi\",\"birthDay\":\"2018-11-05 19:41:47\"}";
  14. String jsonVal2 = "{\"age\":12,\"studentName\":\"wangwu\",\"birthDay\":\"2018-11-05 19:41:47\"}";
  15. User obj0 = JSON.parseObject(jsonVal0, User.class);
  16. System.out.println(obj0);
  17. User obj1 = JSON.parseObject(jsonVal1, User.class);
  18. System.out.println(obj1);
  19. User obj2 = JSON.parseObject(jsonVal2, User.class);
  20. System.out.println(obj2);
  21. }
  22. //输出结果:
  23. User(name=null, birthDay=Mon Nov 05 19:41:47 CST 2018, age=10)
  24. User(name=lisi, birthDay=Mon Nov 05 19:41:47 CST 2018, age=11)
  25. User(name=wangwu, birthDay=Mon Nov 05 19:41:47 CST 2018, age=12)

 发现,JSON串中如果是name的话,反序列化的话会是null。但如果是userName或者studentName的话,则会成功反序列化。

 并且,JSON串中age的值是带引号的"10",也就是String类型,而User类中age是Interger类型,这样也可以反序列化成功。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/982455
推荐阅读
相关标签
  

闽ICP备14008679号