skip to Main Content

I got a response to my request:

[
   {
      "data":{
         "channel":{
            "id":"708087644",            
            "__typename":"User"
         }
      },
      "extensions":{
         "durationMilliseconds":112,
         "operationName":"ViewerCardModLogsMessagesBySender",
         "requestID":"01GWVKPD13BQGBZS64TY4824B9"
      }
   }
]

I am trying to create a Java class where I can parse this response:

ResponseEntity<RestResponse> result = restTemplate.postForEntity(uri, entity, RestResponse.class);

However, I still got an exception:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `org.tomass.twitch.RestResponse` from Array value (token `JsonToken.START_ARRAY`)
 at [Source: (PushbackInputStream); line: 1, column: 1]

RestResponse looks like this:

public class RestResponse implements Serializable {
    private static final long serialVersionUID = 1L;

    private List<Root> root = new ArrayList<>();

    public List<Root> getRoot() {
        return root;
    }

    public void setRoot(List<Root> root) {
        this.root = root;
    }

    public static class Root {

        private Data data;

        // getters & setters

        public class Data {
            private Channel channel;

            // getters & setters
        }
    }
}

When editing the response and the name of the root list then it works: "{"root":
but I don’t know how to parse it without it.

2

Answers


  1. There is no way to explicitly ask RestTemplate to deserialize into List<Root>, but you can ask ObjectMapper! (if you are using Spring, there is one already available in context) The trick is to store type information into TypeReference<T>.

        ObjectMapper mapper = ...;
        ResponseEntity<String> rawResult = restTemplate.postForEntity(uri, entity, String.class);
        List<Root> result = mapper.readValue(rawResult.getBody(), new TypeReference<List<Root>>(){
            /*yes, this is anonymous class*/
        });
    
    Login or Signup to reply.
  2. With RestTemplate you could fetch an array of entities and convert it to a list:

    Root[] rootArray = restTemplate.getForObject(uri, Root[].class);
    List<Root> roots = Arrays.stream(rootArray).collect(Collectors.toList());
    

    If you need an unmodifiable list you could use List.of() or Arrays.asList().


    Converting with ObjectMapper you could do a similar thing:

    ObjectMapper mapper = new ObjectMapper();
    Root[] root = mapper.readValue(myJsonString, Root[].class);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search