user9670036
user9670036

Reputation: 61

How to deserialize a JSON array on client site with Jersey 2.27

This is my code so far:

    public ArrayList<Person> getGames() {

    WebTarget target = webTarget.path("some/path");

    Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);

//        add authentication cookie to get request
    Response response = invocationBuilder.cookie(this.cookie).get();

    int status = response.getStatus();

    if (status == 200) { // everything ok

        // response has wrong MediaType (text/plain from server side)
        // this sets the right MediaType so Jackson (Json deserialization) will handle it
        response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);

//     How do I do this?
       ArrayList<Person> list = response.readEntity(???);

        return list;
    } else {
        return new ArrayList<GameInfo>(); // FIXME: This may throw an exception
    }
}

I know how a single JSON Object is deserialized:

Person person = response.readEntity(Person.class);

and that gets done internally (with Jackson I think).

My problem is, that I get a JSON in the form:

[{"name":"name","age":"age","lives":{"street":"myStreet"}}, .... ]

I suppose it is somehow possible to do this without to much hassle, but I am unable to find any examples that don't use very much outdated versions of Jersey. In the documentation I could not find a paragraph that talks about deserialization of an array.

I appreciate any form of help :)

Upvotes: 1

Views: 1688

Answers (1)

user9670036
user9670036

Reputation: 61

And to answer my own question :

https://www.reddit.com/r/javahelp/comments/7qkvjm/how_to_parse_json_array_with_2_or_more_different/

a big thank you to webdevnick22.

Person[] persons = response.readEntity(Person[].class);

is all you have to do, a simple but hard to find answer.

Upvotes: 3

Related Questions