我正在使用 Spring Boot 和 Spring Framework (spring-boot-starter-parent 2.1.6.RELEASE) 开发一个 Rest Client
我有一个代表响应对象的类,如下所示:
public class ValidateResponse {
private String ResponseCode;
private String ResponseDesc;
//getters and setters
//constructors using fields
//empty constructor
}
我正在为外部 api 创建一个 web-hook,我需要为特定端点返回一个 JSON 对象(JSON 对象属性必须以大写字母开头)。我正在调用从
PostMapping
返回对象嵌套在 RequestMapping
中的方法根路径:@PostMapping("hooks/validate")
public ValidateResponse responseObj(@RequestHeader Map<String, String> headersObj) {
ValidateResponse response = new ValidateResponse("000000", "Success");
logger.info("Endpoint = hooks/validate | Request Headers = {}", headersObj);
return response;
}
但是,当我从 postman 那里到达终点时,我得到了重复的变量
{
"ResponseCode": "000000",
"ResponseDesc": "Success",
"responseCode": "000000",
"responseDesc": "Success"
}
我知道 pojo-json 转换是由 spring 处理的,但我不明白为什么转换会产生重复的变量。
注:我知道
ResponseDesc
和 ResponseCode
没有使用命名变量的最佳标准(camelCasing)声明。我做了一些挖掘,根据 Java Language Specification
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.
和
The "Java letters" include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.
因此,我假设使用
Camelcase
定义变量在语法上是正确的。格式[需要对此进行澄清]。我正在考虑必须手动创建 JSON 对象,但我想先了解这种行为的原因。任何指针表示赞赏。
最佳答案
Jackson
反序列化它遇到的所有公共(public)字段。但是,如果您想要 Jackson
要以您预期的元素名称返回响应(在您的 case 元素中以大写字母开头),请将字段设为 private
并用 @JsonProperty(expected_name_here)
注释它们.您的类文件通常如下所示
public class ValidateResponse {
@JsonProperty("ResponseDesc")
private String responseCode;
@JsonProperty("ResponseDesc")
private String responseDesc;
//getters and setters
//constructors using fields
//empty constructor
}
Note: The getters and setters for these fields should be
public
, otherwiseJackson
won't see anything to deserialize in the class.
关于json - 消除重复的Json元素并检索以大写字母开头的元素名称spring boot/java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57163249/