Как отправить и получить список с помощью resttemplate? - PullRequest
0 голосов
/ 09 апреля 2019

Я хотел бы отправить и получить список объектов, используя RestTemplate.

Я получаю ту же ошибку Cannot deserialize instance of java.util.ArrayList out of START_OBJECT token. Я работал над этим несколько дней, и мне нужно двигаться дальше. Я пытаюсь отправить партию объектов с помощью restTemplate, чтобы об этом позаботился REST api.

Исключительная трассировка:

java.util.concurrent.ExecutionException:
org.springframework.web.client.RestClientException: Error while extracting 
response for type 
[java.util.List<com.rfidreader.async.model.Maybevehicle>] and content type 
[application/json;charset=UTF-8]; nested exception is 
org.springframework.http.converter.HttpMessageNotReadableException: JSON 
parse error: Cannot deserialize instance of `java.util.ArrayList` out of 
START_OBJECT token; nested exception is 
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot 
deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at com.rfidreader.async.AsyncRfidpringApplication.getTagsCheckVehicle(AsyncRfidpringApplication.java:432)
at com.rfidreader.async.AsyncRfidpringApplication.lambda$0(AsyncRfidpringApplication.java:105)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.web.client.RestClientException: Error while extracting response for type [java.util.List<com.rfidreader.async.model.Maybevehicle>] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:115)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:991)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:974)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:725)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:680)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:629)
    at com.rfidreader.async.model.SimpleTaskBatch2.call(SimpleTaskBatch2.java:57)
    at com.rfidreader.async.model.SimpleTaskBatch2.call(SimpleTaskBatch2.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    ... 3 more
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:243)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:225)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:100)
    ... 11 more
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1342)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1138)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1092)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:332)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:265)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:245)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:27)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3084)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:237)
    ... 13 more

Я пытался создать объектный преобразователь, но он не работает.

@Override
public List<Maybevehicle> call() throws Exception {

    String url="url";
    String authString= "user"+":"+"password";
    byte[] encodedAuth= 
    Base64.encodeBase64(authString.getBytes(Charset.forName("US-ASCII")));
    String authHeader="Basic "+new String(encodedAuth);
    HttpHeaders headers = new HttpHeaders();

   headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    headers.set("Authorization", authHeader);
    HttpEntity<List<Maybevehicle>> requestEntity=new 
 HttpEntity<List<Maybevehicle>>(list,headers);
    ResponseEntity<List<Maybevehicle>> 
  results=appRestTemplate2.exchange(url, HttpMethod.GET, requestEntity, 
new ParameterizedTypeReference<List<Maybevehicle>>(){});


    if(results.getStatusCode().is2xxSuccessful()){
        List<Maybevehicle> vehlist=results.getBody();
        return vehlist;
    }else{
        List<Maybevehicle> vehlist=null;
        return vehlist;
    }

}

REST api :

@GetMapping(path="", consumes="application/json", 
produces="application/json")
public List<Maybevehicle> getBmwvehicle2(@RequestBody List<Maybevehicle> vehList){

     List<Maybevehicle> results=bmwService.findMaybeVehicles(vehList);

     return results; 

Я бы хотел принять ответ как list или json array от rest api. Заранее спасибо!

Вот мой Maybevehicle class:

public class Maybevehicle {

private Bmwvehiclemain b;
private String newtaglocation;
private Future<Bmwvehiclemain> e;
private Integer i;
private Integer vehid;
private Maybevehicle veh;

public Maybevehicle(Bmwvehiclemain b, String newtaglocation){
    this.b=b;
    this.newtaglocation=newtaglocation;
}


public Maybevehicle(Integer i, Future<Bmwvehiclemain> e, String 
newtaglocation) {
    // TODO Auto-generated constructor stub
    this.i=i;
    this.e=e;
    this.newtaglocation=newtaglocation;
} 
//getters and setters

1 Ответ

0 голосов
/ 10 апреля 2019

Хотя я не вижу ваш файл MaybeVehicle.class, я столкнулся с аналогичной проблемой и решил ее, добавив

@JsonDeserialize(as = MaybeVehicle.class)
public class MaybeVehicle {
....
}

как JSON - по умолчанию его нельзя десериализовать в коллекцию, поскольку на самом деле это не массив JSON.Так что вам нужно контролировать процесс десериализации.Было бы полезно, если бы вы опубликовали свой объект MaybeVehicle.

...