首页 > 其他分享 >@JsonProperty注解

@JsonProperty注解

时间:2024-04-07 20:23:26浏览次数:19  
标签:JsonProperty 序列化 String value 注解 null class

@JsonProperty注解

序言

@JsonProperty

当一个Java对象转换成Json字符串后,如果不是正确的实际名称有可能会出现异常。比如数据库中的坐标名称是x_axis,而定义Java对象是是xAxis,那么这时就需要使用到@JsonProperty注解,并且配合ObjectMapper.writeValueAsString方法使用去序列化对象成字符串。如下示例demo,

@JsonProperty(value = "", index = 1, access = JsonProperty.Access.xxx)

其中value为成员变量真实名称,index为序列化之后所展示的顺序,access为该对象的访问控制权限。

  1. @Slf4j
  2. public class JsonPropertyDemo {
  3. @Data
  4. @AllArgsConstructor
  5. @NoArgsConstructor
  6. @Builder
  7. @ToString
  8. private static class Coordinate {
  9. @JsonProperty(value = "x_axis", index = 1, access = JsonProperty.Access.WRITE_ONLY)
  10. private String xAxis;
  11. @JsonProperty(value = "y_axis", index = 2, access = JsonProperty.Access.READ_WRITE)
  12. private String yAxis;
  13. @JsonProperty(value = "z_axis", index = 3, access = JsonProperty.Access.READ_WRITE)
  14. private String zAxis;
  15. }
  16. public static void main(String[] args) {
  17. Coordinate coordinate = Coordinate.builder()
  18. .xAxis("113.58")
  19. .yAxis("37.86")
  20. .zAxis("40.05")
  21. .build();
  22. String jsonStr = JSON.toJSONString(coordinate);
  23. log.info("serializes the specified object into its equivalent Json representation :" + jsonStr);
  24. ObjectMapper mapper = new ObjectMapper();
  25. try {
  26. String str = mapper.writeValueAsString(coordinate);
  27. log.info("serialize any Java value as a String : " + str);
  28. Object bean = mapper.readerFor(Coordinate.class).readValue(str);
  29. log.info("read or update instances of specified type : " + bean);
  30. } catch (JsonProcessingException e) {
  31. log.error("error message : " + e);
  32. }
  33. }
  34. }

注解一般都是通过反射拿到对映的成员变量然后再进行增强,@JsonProperty把成员变量序列化成另外一个名称,并且它在序列化和反序列化的过程中都是使用的实际名称。

@JsonAlias

com.fasterxml.jackson.annotation中的@JsonProperty是可以在序列化和反序列化中使用,而@JsonAlias只在反序列化中起作用,指定Java属性可以接受的更多名称。文末链接也有JsonAlias的实例源码,下面就简单举一个例子,

  1. @Slf4j
  2. public class JsonAliasDemo {
  3. @Data
  4. @AllArgsConstructor
  5. @NoArgsConstructor
  6. @Builder
  7. @ToString
  8. private static class Coordinate {
  9. @JsonAlias(value = "x_location")
  10. @JsonProperty(value = "x_axis")
  11. private String xAxis;
  12. @JsonProperty(value = "y_axis")
  13. @JsonAlias(value = "y_location")
  14. private String yAxis;
  15. @JsonProperty(value = "z_axis")
  16. @JsonAlias(value = "z_location")
  17. private String zAxis;
  18. }
  19. public static void main(String[] args) {
  20. String location = "{\"x_location\":\"113.58\",\"y_location\":\"37.86\",\"z_location\":\"40.05\"}";
  21. ObjectMapper mapper = new ObjectMapper();
  22. try {
  23. Object bean = mapper.readValue(location, Coordinate.class);
  24. log.info("read or update instances of specified type : " + bean);
  25. } catch (JsonProcessingException e) {
  26. log.error("error message : " + e);
  27. }
  28. }
  29. }

@JsonAlias里的别名的json字符串,在反序列化时可以识别出来,不会反序列化失败,结果如下图,

@JsonProperty源码

JsonProperty的源码是一个注解类,注解类上的几个元注解就不解释了,可以参考文末链接7,该注解的主要作用就是在pojo属性上执行自定义处理器流程。

  1. @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @JacksonAnnotation
  4. public @interface JsonProperty {
  5. String USE_DEFAULT_NAME = "";
  6. int INDEX_UNKNOWN = -1;
  7. String value() default "";
  8. boolean required() default false;
  9. int index() default -1;
  10. String defaultValue() default "";
  11. JsonProperty.Access access() default JsonProperty.Access.AUTO;
  12. public static enum Access {
  13. AUTO,
  14. READ_ONLY,
  15. WRITE_ONLY,
  16. READ_WRITE;
  17. private Access() {
  18. }
  19. }
  20. }

那么下面就看一下处理器流程做了一些什么事,找到JacksonAnnotationIntrospector类,

先看在jackson 2.6版本之后找到添加了@JsonProperty注解的pojo属性做了什么事,注意这里是一个过期的旧方法,保留是为了兼容使用老版本jackson的方法(@Deprecated注解)。首先该方法通过反射拿到成员变量,然后再获取注解中的属性值(eg:@JsonProperty(value = "x_axis")),如果找到则返回value值,否则就返回原成员变量的name。

  1. /**
  2. * Since 2.6, we have supported use of {@link JsonProperty} for specifying
  3. * explicit serialized name
  4. */
  5. @Override
  6. @Deprecated // since 2.8
  7. public String findEnumValue(Enum<?> value)
  8. {
  9. // 11-Jun-2015, tatu: As per [databind#677], need to allow explicit naming.
  10. // Unfortunately cannot quite use standard AnnotatedClass here (due to various
  11. // reasons, including odd representation JVM uses); has to do for now
  12. try {
  13. // We know that values are actually static fields with matching name so:
  14. Field f = value.getClass().getField(value.name());
  15. if (f != null) {
  16. JsonProperty prop = f.getAnnotation(JsonProperty.class);
  17. if (prop != null) {
  18. String n = prop.value();
  19. if (n != null && !n.isEmpty()) {
  20. return n;
  21. }
  22. }
  23. }
  24. } catch (SecurityException e) {
  25. // 17-Sep-2015, tatu: Anything we could/should do here?
  26. } catch (NoSuchFieldException e) {
  27. // 17-Sep-2015, tatu: should not really happen. But... can we do anything?
  28. }
  29. return value.name();
  30. }

下面再看一下jackson2.7之后是怎么做的,首先该方法不是根据成员变量的name获取类的属性,而是直接遍历类中所有的属性,然后用哈希表expl存属性的name和注解中的value映射关系,然后一次性遍历一遍把所有的属性的真实值集合返回出来(如果没有配置@JsonProperty的value则是属性原值,如果配有@JsonProperty的value则返回value值),这么做的好处在于不用一次一次的解析真实属性值而是一起解析真实属性值。

  1. @Override // since 2.7
  2. public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names) {
  3. HashMap<String,String> expl = null;
  4. for (Field f : ClassUtil.getDeclaredFields(enumType)) {
  5. if (!f.isEnumConstant()) {
  6. continue;
  7. }
  8. JsonProperty prop = f.getAnnotation(JsonProperty.class);
  9. if (prop == null) {
  10. continue;
  11. }
  12. String n = prop.value();
  13. if (n.isEmpty()) {
  14. continue;
  15. }
  16. if (expl == null) {
  17. expl = new HashMap<String,String>();
  18. }
  19. expl.put(f.getName(), n);
  20. }
  21. // and then stitch them together if and as necessary
  22. if (expl != null) {
  23. for (int i = 0, end = enumValues.length; i < end; ++i) {
  24. String defName = enumValues[i].name();
  25. String explValue = expl.get(defName);
  26. if (explValue != null) {
  27. names[i] = explValue;
  28. }
  29. }
  30. }
  31. return names;
  32. }

其他属性的解析也基本上如出一辙,代码如下,

  1. @Override
  2. public Boolean hasRequiredMarker(AnnotatedMember m)
  3. {
  4. JsonProperty ann = _findAnnotation(m, JsonProperty.class);
  5. if (ann != null) {
  6. return ann.required();
  7. }
  8. return null;
  9. }
  10. @Override
  11. public JsonProperty.Access findPropertyAccess(Annotated m) {
  12. JsonProperty ann = _findAnnotation(m, JsonProperty.class);
  13. if (ann != null) {
  14. return ann.access();
  15. }
  16. return null;
  17. }
  18. @Override
  19. public Integer findPropertyIndex(Annotated ann) {
  20. JsonProperty prop = _findAnnotation(ann, JsonProperty.class);
  21. if (prop != null) {
  22. int ix = prop.index();
  23. if (ix != JsonProperty.INDEX_UNKNOWN) {
  24. return Integer.valueOf(ix);
  25. }
  26. }
  27. return null;
  28. }
  29. @Override
  30. public String findPropertyDefaultValue(Annotated ann) {
  31. JsonProperty prop = _findAnnotation(ann, JsonProperty.class);
  32. if (prop == null) {
  33. return null;
  34. }
  35. String str = prop.defaultValue();
  36. // Since annotations do not allow nulls, need to assume empty means "none"
  37. return str.isEmpty() ? null : str;
  38. }

序列化和反序列化配置

另外,序列化和反序列化中会有些常见配置,比如常见的如下,

DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES

在反序列化json字符串成Java对象时,遇到未知属性是否抛出异常信息。

  1. @Slf4j
  2. public class DeserializationFeatureDemo {
  3. /**
  4. * 注意上面的实例对象必须要有无参构造函数,否则在反序列化时创建实例对象
  5. * 会抛出异常com.fasterxml.jackson.databind.exc.InvalidDefinitionException
  6. */
  7. @Data
  8. @Builder
  9. @AllArgsConstructor
  10. @NoArgsConstructor
  11. private static class Person {
  12. private String name;
  13. private Long age;
  14. }
  15. public static void main(String[] args) {
  16. String jsonStr = "{\"name\":\"张三\",\"age\":18,\"sex\":\"男\"}";
  17. System.out.println("serialize java object to json : " + jsonStr);
  18. Person A = parse(jsonStr, Person.class, false);
  19. System.out.println("after deserialize to object :" + JSON.toJSONString(A));
  20. Person B = parse(jsonStr, Person.class, true);
  21. System.out.println("after deserialize to object :" + JSON.toJSONString(B));
  22. }
  23. private static <T> T parse(String json, Class<T> tClass, boolean failOnUnknownProperties) {
  24. ObjectMapper objectMapper = new ObjectMapper();
  25. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties);
  26. T result = null;
  27. try {
  28. result = objectMapper.readValue(json, tClass);
  29. } catch (JsonProcessingException e) {
  30. log.error("Failed to deserialize JSON content, json value : " + json);
  31. }
  32. return result;
  33. }
  34. }

可以看到输出结果,配置设为true时在反序列化未知属性直接抛出异常信息,

 JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS

是否允许JSON字符串包含非引号控制字符(值小于32的ASCII字符,包含制表符和换行符)。 由于JSON规范要求对所有控制字符使用引号,这是一个非标准的特性,因此默认禁用。

更多配置参考文末链接6。

参考链接:

1、JSON在线 | JSON解析格式化—SO JSON在线工具

2、JsonProperty (Jackson JSON Processor)

3、Java类com.fasterxml.jackson.annotation.JsonProperty的实例源码 - 编程字典

4、Java类com.fasterxml.jackson.annotation.JsonAlias的实例源码 - 编程字典

5、Jackson data binding - 知乎

6、4. JSON字符串是如何被解析的?JsonParser了解一下(中)-阿里云开发者社区

7、注解的使用_四问四不知的博客-CSDN博客

原文链接:https://blog.csdn.net/zkkzpp258/article/details/125120601

标签:JsonProperty,序列化,String,value,注解,null,class
From: https://www.cnblogs.com/sunny3158/p/18119792

相关文章

  • Java(1)——注解
    常用注解Java注解从Java1.5开始引入,注解就是代码中的特殊标记,告诉类要如何运作。注解的典型应用是:通过反射技术获得类中的注解,来决定如何运行类。注解可以标记在类、属性、方法、变量等,并且一个地方可以同时标记多个注解。先从一个简单的注解开始说起。classSuperClass{......
  • SSM(Spring+SpringMVC+MyBatis)常用注解大全
    提示使用浏览器查找系统也快速查找,可避免漏看和疲劳Win:Ctrl+FMac:Command+F@Bean功能:用于在配置类中声明一个bean。用法:@ConfigurationpublicclassAppConfig{@BeanpublicMyServicemyService(){returnnewMyServiceImpl();}}@Com......
  • 注解和注释区别
    在Java中,"Annotation"通常被翻译为“注解”,而不是“注释”。虽然“注解”和“注释”这两个词在中文中很相似,但在编程语境中它们有着不同的含义和用途。注释(Comment):注释主要用于解释代码的功能、用途或特殊情况,帮助开发者理解代码。它们不会被编译器编译进程序,也不会影响程序的执......
  • easyExcel通用导出(非注解,多线程)
    1、基础类描述ExcelWriter(导出工具类)Query(通用查询)Consumer(函数参数)SpringBeanUtil(获取bean)2、代码ExcelWriterimportcn.hutool.core.collection.CollUtil;importcn.hutool.core.collection.ListUtil;importcn.hutool.core.util.PageUtil;importcn.hutool.core.u......
  • Spring 注解编程之 AnnotationMetadata
    Spring注解编程之AnnotationMetadata这篇文章我们主要深入AnnotationMetadata,了解其底层原理。Spring版本为5.1.8-RELEASEAnnotationMetadata结构使用IDEA生成AnnotationMetadata类图,如下:AnnotationMetadata存在两个实现类分别为StandardAnnotationMeta......
  • Lombok常用注解详解: val, @Cleanup, @RequiredArgsConstructor
    From: https://blog.csdn.net/hy6533/article/details/131030094从零开始SpringBoot35:Lombok图源:简书(jianshu.com)Lombok是一个java项目,旨在帮助开发者减少一些“模板代码”。其具体方式是在Java代码生成字节码(class文件)时,根据你添加的相关Lombok注解或类来“自动”添加......
  • Swagger工具集及Swagger工具集常见注解和用法
    目录一、什么是Swagger工具集二、swagger常用的注解和用法@Api@ApiOperation@ApiParam@ApiModel@ApiModelProperty@ApiIgnore三、常见问题1.@ApiModelProperty和@ApiOperation有什么区别?一、什么是Swagger工具集Swagger工具集是一系列围绕OpenAPISpecification......
  • Type注解对象类型
    Type注解对象在TS中对于对象数据的类型注解,除了使用interface之外还可以使用类型别名来进行注解,作用相似typePerson={name:stringage:number}letpeople:Person={name:'张三',age:16}console.log(people)Type继承type同样也可......
  • Java:注解
    Java中的注解(Annotations)是一种用于提供元数据的特殊接口,它们可以被用于给代码添加信息,而这些信息可以在编译时、类加载时或运行时被读取,并且可以影响程序的行为。注解不会直接影响程序的逻辑,但它们可以被编译器或运行时环境用来生成额外的代码、进行类型检查或者在运行时进......
  • @ComponentScan注解 -【Spring底层原理
    案例已上传GitHub,欢迎star:https://github.com/oneStarLR/spring-annotation一、注解用法1.背景知识什么是组件?组件也是抽象的概念,可以理解为一些符合某种规范的类组合在一起就构成了组件,他可以提供某些特定的功能,但实际他们都是类,只不过有他们特殊的规定。组件......