@JsonProperty注解解析

1. 概述

来源: 
	@JsonPrpperty是jackson包下的一个注解,详细路径
	(com.fasterxml.jackson.annotation.JsonProperty;)

作用:
	@JsonProperty用在属性上,将属性名称序列化为另一个名称。

例子:
	public class Person{
		@JsonProperty(value = "name")
		private String realName;

	}

拓展:jackson可以理解为java对象和json对象进行转化的工具包。

2. 实例

解释:定义一个实体类,定义一个Controller层,通过post请求传入body,分别验证加和不加@JsonProperty注解的区别。

2.1 引入依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
</dependency>

2.2 创建实体类

package com.gxn.demo.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
/**
 * @author gxn
 */

public class Person {
//  先将该注解注释掉
//  @JsonProperty(value = "name")
    private String realName;
    private Integer age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) 
        	return false;
        Person person = (Person) o;
        return Objects.equals(realName, person.realName) &&
                Objects.equals(age, person.age);
    }

    @Override
    public int hashCode() {
        return Objects.hash(realName, age);
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

2.3 定义Controller,返回结果是realName和age的值

package com.gxn.demo.controller;

import com.gxn.demo.domain.Person;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author gxn
 */
@RestController
public class PersonController {

    @PostMapping("/name")
    public String getName(@RequestBody Person person) {
        String name = person.getRealName();
        Integer age = person.getAge();
        String res = name + " : " + age;
        return res;
    }

}

2.4 验证结果

  • 未加注解,body中json的key和实体属性一致:
    在这里插入图片描述

  • 未加注解,body中json的key和实体属性不一致:
    在这里插入图片描述

  • 加注解,body中json的key和实体属性一致:
    在这里插入图片描述
    在这里插入图片描述

  • 加注解,body中json的key与注解的value一致::
    在这里插入图片描述

3. 总结

通过@JsonProperty注解可以改变实体对应属性名,一旦使用该注解我们在body中传参数的就需要按照注解中value的值来定义key。

@JsonProperty 注解的实现源码涉及到 Jackson 库的具体实现。以下是伪代码形式的实现源码详解: ```java // 定义 @JsonProperty 注解 public @interface JsonProperty { String value(); } // 序列化过程中,将 Java 对象属性值转换为 JSON 字符串 public class JsonSerializer { public String serialize(Object object) { // 获取对象的类信息 Class<?> clazz = object.getClass(); // 获取对象的属性列表 List<Field> fields = getFields(clazz); // 创建一个 JSON 对象 JsonObject json = new JsonObject(); // 遍历属性列表 for (Field field : fields) { // 检查属性是否带有 @JsonProperty 注解 if (field.isAnnotationPresent(JsonProperty.class)) { // 获取 @JsonProperty 注解的值作为字段名称 String fieldName = field.getAnnotation(JsonProperty.class).value(); // 获取属性值 Object value = getValue(object, field); // 将字段名称和属性值添加到 JSON 对象中 json.addProperty(fieldName, value); } } // 将 JSON 对象转换为字符串 return json.toString(); } // 反序列化过程中,将 JSON 字符串转换为 Java 对象属性值 public <T> T deserialize(String jsonStr, Class<T> clazz) { // 创建一个空的 Java 对象 T object = createObject(clazz); // 创建一个 JSON 对象 JsonObject json = parseJson(jsonStr); // 获取对象的属性列表 List<Field> fields = getFields(clazz); // 遍历属性列表 for (Field field : fields) { // 检查属性是否带有 @JsonProperty 注解 if (field.isAnnotationPresent(JsonProperty.class)) { // 获取 @JsonProperty 注解的值作为字段名称 String fieldName = field.getAnnotation(JsonProperty.class).value(); // 获取 JSON 字段对应的值 Object value = json.get(fieldName); // 设置属性值 setValue(object, field, value); } } return object; } // 获取对象的属性列表 private List<Field> getFields(Class<?> clazz) { List<Field> fields = new ArrayList<>(); // 递归获取所有父类的属性列表 while (clazz != null) { fields.addAll(Arrays.asList(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } return fields; } // 获取属性值 private Object getValue(Object object, Field field) { // 设置属性可访问 field.setAccessible(true); try { // 获取属性值 return field.get(object); } catch (IllegalAccessException e) { e.printStackTrace(); return null; } } // 设置属性值 private void setValue(Object object, Field field, Object value) { // 设置属性可访问 field.setAccessible(true); try { // 设置属性值 field.set(object, value); } catch (IllegalAccessException e) { e.printStackTrace(); } } // 创建对象 private <T> T createObject(Class<T> clazz) { try { // 使用默认构造函数创建对象 return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); return null; } } // 解析 JSON 字符串为 JSON 对象 private JsonObject parseJson(String jsonStr) { // 使用 JSON 解析解析 JSON 字符串为 JSON 对象 return JsonParser.parseString(jsonStr).getAsJsonObject(); } } ``` 以上是对 @JsonProperty 注解实现的伪代码解释。实际的 Jackson 库源码实现更为复杂和完善,涉及到更多细节和性能优化。如果需要深入了解可以参考 Jackson 库的源码。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值