首页 > 解决方案 > 使用 Jackson将作为列表或对象的 JSON 内容解析为列表

问题描述

标签: javajackson

解决方案


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)
    );
}

其中 Resp 是一个

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 + '\'' +
                '}';
    }
}

推荐阅读