Search code examples
javajsonrestresteasy

Unmarshal a Json Array in a Json List


I need to get the list of all the films.

i am in this situation and i dont know how to manage it. My project is divided in two smaller project. Back-end project and front-end project. Back-end part that produce a Json that contains a list of films.

The service has this pattern

@GET
@Produce(json)  // here is a particular library and it funcion correctly.
List<Film> getAllFilms

The output calling this service has this pattern:

[{"title:abc","time": 5486448}, {....}, {....}]

At the Front-end project i am using Resteasy . I have create a class service to call the back-end and to manage the response

    List<Film> film= new ArrayList<>();
    try{
    ResteasyClient client = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = client.target("http://localhost:8080/film");


    Response response = target.request().get();
    film=  List<Film>) response.readEntity(Film.class);

I have an exception of this type:

javax.ws.rs.ProcessingException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of FILM out of START_ARRAY token

Now i am trying to understand something but there is full of material and i am loosing around. How can i unmarshall an array to a list ?


Solution

  • You can use readValue method of jackson to convert it to List

    public List<Film> convert(String jsonString) throws JsonParseException, JsonMappingException,
                IOException {
    
            ObjectMapper objectMapper = new ObjectMapper();
    
            List<Film> filmList = objectMapper.readValue(
                    jsonString,
                    objectMapper.getTypeFactory().constructCollectionType(
                            List.class, Film.class));
    
       return filmList;
        }