【发布时间】:2020-01-20 10:23:01
【问题描述】:
我正在尝试使用 springboot 从请求正文中解析 JSON:
下面是邮递员的请求(请求体,类型为application/json)->
{
"CreditComplex": [{
"BCNR":"973",
"RelationshipName":"Pricing Company BV",
"Borrowers":[{
"Borrower ":[{
"BCNR" : "",
"CGC":"1174",
"UCR":"4+",
"PD":"0.03",
"AGIC":"1301",
"BookingLocation":"NL",
"SalesTurnover":"10000000000",
"Facilities": [{
"Facility": [{
"gfid " : "",
"limit": "1000000",
"producttype": "19",
"spread": "3.0000",
"commitmentFee": "0.3000",
"annualfee": "0",
"oneOfffee": "5000",
"lgd": "0.1800",
"outstanding": "500000"
}]
}]
}]
}]
}]}
post方法处理来自springboot的请求
@RequestMapping(path = "/checkjson", method = RequestMethod.POST)
public ResponseEntity<CreditComplex> getBook(@RequestBody CreditComplex creditcomplex) {
return new ResponseEntity<>(creditcomplex, HttpStatus.OK);
}
我创建了以下类来映射 JSON 中的值:
public class CreditComplex {
private String BCNR;
private String RelationshipName;
List<Borrower> borrower;
所有字段都有getter和setter
public class Borrowers {
List <Borrower> borrower;
所有字段都有getter和setter
public class Borrower {
private String BCNR;
private String CGC;
private String UCR;
private String PD;
private String AGIC;
private String BookingLocation;
private String SalesTurnover;
private String Spread;
private String CommitmentFee;
private String AnnualFee;
private String OneOffFee;
private String LGD;
private String Outstanding;
List<Facilities> facilities;
所有字段都有getter和setter
public class Facilities {
private List<Facility> facility;
所有字段都有getter和setter
public class Facility {
private String gfid;
private String limit;
private String producttype;
private String spread;
private String commitmentfee;
private String annualfee;
private String oneOfffee;
private String lgd;
private String outstanding;
with getter and setter for all fields
预期响应是实际请求 json 已映射到 Credit 复杂类但得到如下响应:
{
"borrower": null,
"bcnr": null,
"relationshipName": null
}
任何发现/帮助将不胜感激。
【问题讨论】:
-
你的 JSON 结构很奇怪。我不明白为什么你有像
Borrowers和Facilities这样的中间类,它们只是包装了Borrower和Facility的列表。这可以大大简化 -
是的,这很奇怪,但他似乎没有使用那些“包装”。这里的问题可能是属性名称不匹配(JSON 与 Java)。当您的序列化程序将查找名称为
Borrowers的属性时,它不会找到它,因为您在CreditComplex类中将其称为borrower。以这种方式检查您的代码。并且请不要以大写开头的属性名称,这是不可读的。编辑:没有注意第一个模型。按照akortex91的说法,太复杂了,和你的java模型结构不匹配。 -
嗨,感谢您的 cmets/调查结果。虽然这个例子有一个实时借款人和设施,但会有多个借款人和设施,因此它被命名为单独的。
-
在我最初的帖子中,有一个错误是我在 Creditcomplex 类中使用了 Borrower 而不是 Borrowers。然而,通过使其成为借款人,它也不起作用。有效的是@akortex91 提到的格式,但在这种情况下,我如何在借款人下拥有多个借款人部分,在设施下拥有多个设施部分。举个例子会有所帮助。