java - 为什么 JSON 没有被解组到我的 Java 类中?
问题描述
我正在使用 Spring Boot 和 RestTemplate 从内部服务获取数据。我返回的 JSON 响应没有被解组到我的对象中,我无法弄清楚原因。(我正在使用其他类似的 REST API 并且这些 API 正在工作,所以我以前做过。)
发出请求的代码是标准的东西:
public ChecklistResponse getCurrentStatus(String studentId) {
RestTemplate restTemplate = createRestTemplate();
HttpHeaders httpHeaders = this.createHeaders();
String url = this.createItemStatusUrl(studentId);
ResponseEntity<ChecklistResponse> responseEntity = restTemplate.exchange(url, HttpMethod.GET,
new HttpEntity<>(httpHeaders), ChecklistResponse.class);
ChecklistResponse checklistResponse = responseEntity.getBody();
return checklistResponse;
}
整个对象树很大,所以我不能在这里真正展示出来。ChecklistResponse 很简单,不过:
public class ChecklistResponse {
private HttpStatus httpStatus;
private String responseType;
private Response response;
public ChecklistResponse() {
}
... getters/setters, equals, hashCode, toString ...
}
JSON 响应的开头如下所示:
{
"httpStatus": {
"code": "200",
"description": "OK"
},
"responseType": "namespaceURI=\"http://bmeta.xxx.com/student/studentChecklistV0.xsd\" element=\"studentChecklist\"",
"response": {
"studentChecklist": {
"identifier": {
我设置了拦截器来验证我是否收到了回复。我也在禁用拦截器的情况下运行它,所以我知道它没有消耗响应(尽管我在其他地方成功地使用了拦截器并且对象正在正确解组。)
我的问题是,我该如何调试这个问题?我试过启用杰克逊调试,但没有产生任何结果。我在整个 ChecklistResponse 类中设置了断点,但它没有命中任何一个。
解决方案
很可能你忘了添加公共无参数构造函数,添加一个这样的:
public ChecklistResponse(){}
您应该将这些构造函数添加到对象树中的所有类中。
Another thing to look at is if the issue is a result of the values in the JSON object, ex, unescaped quotation etc .. try to make a unit test with a mocked object with trivial values but none empty/null ones and see if that test can pass or not, case sensitive issues sometimes cause this to fail as well, set break points in the getters/setters, these should be called in the process, make sure they are public as well as the classes themselves, final thing I can think of is the circular reference, make sure you don't have that as well in your object as this will cause issues.
推荐阅读
- r - R中的数据框,不同的行数和列数
- email - 我可以为我的新域购买电子邮件地址吗?
- java - 通过 JLabel 将图像添加到 JWindow 不会出现在屏幕上
- git - 恢复 git lfs 存储
- python - 根据来自其他 DF 的值选择 DF 行
- twitter - Twitter 身份验证在本地工作,但在 Vercel 服务器中不工作 (Next.JS)
- c++ - 从 C++ 协程中获取协程句柄的最有效方法
- reporting-services - SSRS 从 SQL 存储过程返回值获取结果
- javascript - 使用外部 javascript 代码在 Chrome 控制台上运行代码段
- android-studio - Android Studio 应用程序图标未在新的 Android 模型中显示