Jackson JSON反序列化兼容JSON对象和字符串

案例一

1
no String-argument constructor/factory method to deserialize from String val
1
2
3
4
5
6
:Failed
to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Cannot construct instance of `com.example.demo.model.Customer`
(although at least one Creator exists): no String-argument constructor/factory
method to deserialize from String value
('{"id":0,"name":"Joe","city":"HangZhou","contactNum":123456}');

在spring boot前端访问接口突然出现上述错误,后台接收参数接收到了字符串,导致不能反序列化。但是前端代码看不出任何问题。

解决办法:增加一个构造函数来手动赋值

1
2
3
4
5
6
7
public SubmitParam(String json) throws IOException {
SubmitParam param = new ObjectMapper().readValue(json, SubmitParam.class);
this.id = param.getId();
this.name = param.getName();
this.city = param.getCity();
this.contactNum = param.getContactNum();
}

案例二

1
no String-argument constructor/factory method to deserialize from String value ('null')
1
2
3
4
5
6
org.springframework.web.client.RestClientException: 
Error while extracting response for type [class cn.appblog.provider.channel.channels.kbank.model.response.QrPayQueryResponse] and content type [application/json;charset=UTF-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Cannot construct instance of `cn.appblog.provider.channel.channels.kbank.model.Metadata` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('null');
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException:
Cannot construct instance of `cn.appblog.provider.channel.channels.kbank.model.Metadata` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('null')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"id":"chrg_prod_609e6d56f22797e82d2b7630ac7962766bf",
"object":"charge",
"created":"20210331185005000",
"livemode":true,
"amount":3179,
"currency":"THB",
"description":"VEMAR I ผู้นำแฟชั่นให้ผู้หญิงยุคใหม่ กระเป๋าชิคที่ไม่ซ้ำใคร - #20180677492802",
"metadata":"null",
"source":{
"id":"qr_prod_4098550e5d3659740f69c974449e85c9bc1",
"object":"qr",
"brand":"ThaiQR",
"card_masking":null,
"issuer_bank":null
},
"status":"success",
"order_id":"order_prod_6094ef376fe68cd8e90aa00810e7a53fce7",
"transaction_state":"Settled",
"reference_order":"182021033100920298",
"failure_code":null,
"failure_message":null
}
1
2
3
4
5
6
7
8
9
10
11
12
13
@Data
@NoArgsConstructor
public class Metadata {
private String item;
private String qty;
private String amount;

public Metadata(String json) throws IOException {
this.item = null;
this.qty = null;
this.amount = null;
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :