首页 > 解决方案 > 使用@JsonAlias 使用@RequestBody 转换成Pojo

问题描述

我有如下给出的 JSON 模式,

{
    "prty_id": "hgh",
    "customer_id": "ghjghjghj"
}

我有下面给出的模型类

public class PARTY   {
    @JsonAlias({"prty_id", "prtyId"})
    String prtyId;

    @JsonAlias({"customer_id", "customerId"})
    String customerId;
    ......
}

当我尝试@RequestBody使用 PARTY 主体作为方法参数的注释反序列@RequestBody化时,我得到 POJO 类字段的空值。

@PostMapping(value="/party/db",produces="application/json",consumes="application/json")


public Party controller(@RequestBody Party body)
//here in body parameter only i am getting null values
                {
                    ObjectMapper obj = new ObjectMapper();
                    String json = obj.writeValueAsString(body);
                    System.out.println("===="+json);

                    PARTY p = obj.readValue(json, PARTY.class);
                    System.out.println("------"+p);
                    p.toString();
                    return p;
                }

标签: javajson

解决方案


您需要在课堂上编写吸气剂,以便杰克逊去串行化可以工作。在您的定义中也更好地使用 CamelCase:

public class Party {

    @JsonAlias({"prty_id", "prtyId"})
    String prtyId;

    @JsonAlias({"customer_id", "customerId"})
    String customerId;

    public String getPrtyId() {
        return prtyId;
    }

    public String getCustomerId() {
        return customerId;
    }
}

编辑:添加控制器:

@PostMapping("/test")
public Party test(@RequestBody Party body) {
    return body;
}

推荐阅读