Matthisk
Matthisk

Reputation: 1521

Parse JSON content that is either list or object as List<A> using Jackson

An inconsistent JSON api returns me either a list of objects by some type or a single instance of this object type. I want to create a generic method that is capable of parsing this content as a List<A> (using Jackson).

So for example, the first variant would be:

{ "error": "message" }

And the second variant:

[{ "error": "message" }, /* ... */]

The type signature of my method would have to look something like this:

<A> List<A> eitherObjectOrList(String content, Class<A> c);

Upvotes: 3

Views: 588

Answers (1)

Anatoly Samoylenko
Anatoly Samoylenko

Reputation: 701

public static void main(String[] args) throws Exception {
    String oneJson = "{ \"error\": \"message\" }";
    String arrJson = "[{ \"error\": \"message\" }, { \"error\": \"message2\" }]";
    List<Resp> result = eitherObjectOrList(oneJson, Resp.class);
    System.out.println(result);
    result = eitherObjectOrList(arrJson, Resp.class);
    System.out.println(result);
}

public static <A> List<A> eitherObjectOrList(String content, Class<A> c) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    return mapper.readValue(
            content,
            mapper.getTypeFactory().constructCollectionType(List.class, c)
    );
}

where Resp is a

public static class Resp {
    private String error;

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    @Override
    public String toString() {
        return "Resp{" +
                "error='" + error + '\'' +
                '}';
    }
}

Upvotes: 2

Related Questions