@JsonProperty注解和@SerializedName注解

两个都是使web项目对象中的属性符合驼峰式命名

—————————————————————————————————————————————————

1. Student类:

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class Student {
    @JsonProperty("stuName")
    private String name;
    @JsonProperty("stuAge")
    private Integer age;
}

2.StudentController类:

import com.example.demo.pojo.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentController {
    @RequestMapping("/student")
    public Student getStudent(){
        Student student = new Student();
        student.setName("张三");
        student.setAge(100);
        return student;
    }
}

3.  启动项目

得到是数据是:

{"stuName":"张三","stuAge":100}

这就是注解内的内容。

 

4. 因为有时候前端转到得到 json数据不尽人意会出现转换后:

{studentName:张三,studentAge:25} 如此的json数据

在Controller添加:

@RequestMapping("/student2")
public Student getStudentByJson(){
    Gson gson = new Gson();
    String studentJson = "{studentName:张三,studentAge:25}";
    Student  stu = gson.fromJson(studentJson,Student.class);
    return stu;
}

访问得到:

{"stuName":null,"stuAge":null}

5:加入@SerializedName注解

@Data
public class Student {
    @JsonProperty("stuName")
    @SerializedName("studentName")
    private String name;
    @SerializedName("studentAge")
    @JsonProperty("stuAge")
    private Integer age;
}

再次访问项目:

{"stuName":"张三","stuAge":25}

6.  总结:

@JsonProperty使对象属性输出为@JsonProperty内的内容。

@SerializedName使对象属性序列化为想要的值

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值