使用 RestTemplate 进行部分 JSON 检索

Partial JSON retrieval with RestTemplate

我正在使用 Spring RestTemplateGET request 发送到第三方服务。它returns巨大JSON代表了list of some entities。但每个实体都非常大,包含大量不必要的数据。我只需要从每个实体获取三个字段。我怎样才能建立我的模型来实现它?例如,如果我们有这个 JSON:

{
   "entity1": "foo",
   "entity2": "bar",
   "entity3": "...",
   "entity4": {
       "aaa": "...",
       "bbb": "...",
       "ccc": 5
   },
   "entity5": [
       "...",
       "..."
   ]
}, {
   "entity1": "foo",
   "entity2": "bar",
   "entity3": "...",
   "entity4": {
       "aaa": "...",
       "bbb": "...",
       "ccc": 5
   },
   "entity5": [
       "...",
       "..."
   ]
}

我有一个 class:

public class SomeModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long entity1;
    private String entity2;    
}

如何将此 JSON 转换为此 class 的实例数组?

如果您使用的是 Jackson,则可以使用 @JsonIgnoreProperties(ignoreUnknown = true) 注释您的模型 class,例如:

@JsonIgnoreProperties(ignoreUnknown = true)
public class PosterDishModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long entity1;
    private String entity2;    
}

基本上,它指示 Jackson 丢弃接收到的对象中的任何未知属性。

请注意,这不会阻止整个对象通过网络传输,流量将相同,但反序列化的对象不会包含不必要的字段和数据。