JAX-RS调用REST API时因JSON格式变更无法解析为POJO
问题解决:JSON结构变更后的JAX-RS客户端解析失败
你遇到的问题确实是因为JSON返回结构改变导致的——原来的接口直接返回Entity数组,现在返回的是一个包含Entity数组(elements字段)和总数(total字段)的顶层对象。Jackson反序列化时期望根节点是数组([),但实际收到的是对象({),所以才会报Can not deserialize instance of myproject.pojo.Entity[] out of START_OBJECT token错误。
下面是两种可行的解决方案:
方案一:创建匹配新JSON结构的包装POJO(推荐)
新建一个包装类来对应新的JSON返回结构,通过它来间接获取Entity列表:
1. 新增EntityResponse类
@JsonIgnoreProperties(ignoreUnknown = true) public class EntityResponse { private List<Entity> elements; private int total; // Jackson反序列化必须要有无参构造器 public EntityResponse() {} // getter & setter public List<Entity> getElements() { return elements; } public void setElements(List<Entity> elements) { this.elements = elements; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } }
2. 修改客户端解析方法
先解析成EntityResponse对象,再从中提取elements列表:
public List<Entity> getEntities() { EntityResponse response = target.path("entities") .request(MediaType.APPLICATION_JSON) .get(EntityResponse.class); return response.getElements(); }
如果需要返回数组,可改为:
public Entity[] getEntities() { EntityResponse response = target.path("entities") .request(MediaType.APPLICATION_JSON) .get(EntityResponse.class); return response.getElements().toArray(new Entity[0]); }
方案二:手动解析JSON(无需新增POJO)
如果不想创建新类,也可以用JAX-RS自带的JsonObject手动提取数据:
import javax.json.JsonObject; import javax.json.JsonArray; import java.util.stream.Stream; public Entity[] getEntities() { JsonObject jsonObject = target.path("entities") .request(MediaType.APPLICATION_JSON) .get(JsonObject.class); JsonArray elementsArray = jsonObject.getJsonArray("elements"); // 将JsonArray转换为Entity数组 return elementsArray.stream() .map(jsonValue -> jsonValue.asJsonObject()) .map(jsonObj -> { Entity entity = new Entity(); entity.setKey(jsonObj.getString("key")); return entity; }) .toArray(Entity[]::new); }
这种方式适合临时场景,当Entity字段较多时,维护成本会比POJO方式高。
补充说明
你之前尝试的GenericEntity<List<Entity>>之所以失败,是因为它依然期望根节点是List类型的数组结构,但实际返回的是包含List的顶层对象,Jackson依然会因为根节点类型不匹配报错。
内容的提问来源于stack exchange,提问作者user2756894
相关产品推荐
相关产品推荐

