我是第一次使用JacksonAPI。我创建了一个spring Boot 应用程序,并尝试更改JSON字符串的键。
package com.poc.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Employee {
@JsonProperty("employeeId")
private Integer id;
@JsonProperty("employeeName")
private String name;
}
--------------------------------
package com.poc.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.poc.entity.Employee;
@RestController
@RequestMapping("/emp")
public class EmployeeController {
@GetMapping
public ResponseEntity<Employee> get() throws JsonMappingException, JsonProcessingException {
String json = "{ \"employeeId\" : \"123\", \"employeeName\" : \"John Smith\" }";
ObjectMapper mapper = new ObjectMapper();
Employee employee = mapper.readValue(json, Employee.class);
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
}
预期结果:{“id”:123,“name”:“John Smith”}
但它给予:{“employeeId”:123,“employeeName”:“John Smith”}
请帮我修理一下。提前感谢您的帮助。
2条答案
按热度按时间a2mppw5e1#
通过将注解应用于属性,您可以将其应用于setter(用于从JSON到Java对象的阅读)和getter(用于序列化-将Java对象转换为JSON)。
您需要在getter和setter上使用
@JsonProperty
,并相应地定义每个值:flvlnr442#
不幸的是,当使用Lombok时,@Getter和@Setter或@Data注解将在编译时创建getter和setter方法,并且这些方法将具有基于字段名称的标准命名约定。如果您想对同一个字段的getter和setter使用不同的@JsonProperty注解(这是不常见的),则不能对该字段使用Lombok的注解。您必须手动定义getter和setter。