json是這樣的結構:
{
"data": [{"id":"1", "name": "foo"]
}
我有一個形式為DTO的檔案
class Domain {
字串id。
字串域。
}
我想將陣列決議為List并忽略資料。以下是代碼:
@WithUserDetails("testuser")
@Test
public void test_get_domains_api() {
HttpHeaders headers = new HttpHeaders() 。
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON))。
headers.add("User-Agent", "Spring's RestTemplate" ) 。
headers.add("Authorization", "Bearer" TOKEN ) 。
ResponseEntity<Map<String, List<Domain>> response = restTemplate.exchange(
"https://sample/v1/sites"。
HttpMethod.GET,
new HttpEntity<>("引數", headers),
Map<String, List<Domain> >.class
);
System.out.println(response.getBody())。
assertNotNull(response)。
}
但是我得到了這個例外
Error while extracting response for type [class [Lcom.commengine.entity.domain;]
和內容型別[application/json]。
嵌套的例外是org.springframework.http. converter.HttpMessageNotReadableException。
JSON決議錯誤。
無法反序列化[Lcom.commengine.entity.Domain;out of START_OBJECT]的實體。
token;嵌套的例外是
com.fastxml.jackson.databind.ex.MismatchedInputException。無法反序列化
的實體不能被反序列化[Lcom.commengine.entity.Domain; out of START_OBJECT token
在[Source: (PushbackInputStream); line: 1, column: 1]
uj5u.com熱心網友回復:
我建議你改變你的模型如下:
class ResponseDomainData {
串列<域>資料。
}
class Domain {
字串id。
字串名稱。
}
而你的測驗也是:
@WithUserDetails("testuser")/span>
@Test
public void test_get_domains_api() {
HttpHeaders headers = new HttpHeaders() 。
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON))。
headers.add("User-Agent", "Spring's RestTemplate" ) 。
headers.add("Authorization", "Bearer" TOKEN ) 。
回應Entity<ResponseDomainData> response = restTemplate.exchange(
"https://sample/v1/sites",
HttpMethod.GET。
new HttpEntity<>("引數", headers)。
回應DomainData.class
);
System.out.println(response.getBody())。
assertNotNull(response)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/332448.html
標籤:
