json - 消除重复的Json元素并检索以大写字母开头的元素名称spring boot/java

标签 json spring-boot jackson type-conversion pojo

我正在使用 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 处理的,但我不明白为什么转换会产生重复的变量。

注:我知道ResponseDescResponseCode没有使用命名变量的最佳标准(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, otherwise Jackson won't see anything to deserialize in the class.

关于json - 消除重复的Json元素并检索以大写字母开头的元素名称spring boot/java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57163249/

相关文章:

json - 使用 jq 解析两个列表中存在的键(即使其中一个列表中可能不存在)

javascript - 如果可能,将嵌套 JSON 结构中的每个对象重命名为其 .name 属性

java - DateTimeFormatter 可以格式化日期,但无法读取其自身的格式

java - 在 Jackson 中反序列化 bson long 原始 json

java - 在 spring-boot 中使用 2 个数据库时出现问题。无法 Autowiring 。未找到 EntityManagerFactoryBuilder 的 beans

java - 使用 RestTemplate 时出错 - 使用 Apache Commons Multimap 反序列化对象时出现问题

javascript - 使用 javascript 在 Internet Explorer 中迭代 formData 对象

python - 使用 Python 将字典写入 JSON

java - Netflix Hystrix - HystrixObservableCommand 异步运行

java - 通过 Kafka 发送/接收 Java 对象