两个都是使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使对象属性序列化为想要的值
本文探讨了在Java中如何使用@JsonProperty和@SerializedName注解确保Web项目对象属性符合驼峰命名规范,特别是在前后端交互中处理JSON数据时的转换问题。
1311

被折叠的 条评论
为什么被折叠?



