如何从 REST post 请求中解析 Json 数组

How to parse Json Array from REST post request

如何解析 JSON 数组以列出对象。来自我调用请求的另一个系统的客户端正在消耗正文 JSON 并返回响应

List<Model1>

作为JSON。当我调用此请求时,我想获得此响应并将其转换为列表(在我的系统中)。我知道列表中包含的对象的结构,所以我准备了 POJO class 来将 model1 解析为 model2。我是否需要将我的 Model2 class(我系统中的 POJO)包装到另一个 class?

我正在使用 WebTarget,URL 已完成,看起来像这样:

WebTarget wt = target();

 wt.path(URL)
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(consumedBody,MediaType.APPLICATION_JSON), Model2);

或者我应该使用包含一个字段和 List 的包装 class,我们称其为 WrapperModel2

 wt.path(URL)
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(consumedBody,MediaType.APPLICATION_JSON), WrapperModel2);

每次我收到错误提示“无法将 JSON 数组解析为:Model2 或 WrapperModel2。正确解析 Json 数组为特定对象列表的方法是什么?

我相信你正在使用 JAX-RS,所以你可以试试这个吗:

.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE), new GenericType<List<Model2>>() {
        });