【问题标题】:Partial JSON retrieval with RestTemplate使用 RestTemplate 检索部分 JSON
【发布时间】:2016-08-11 13:27:31
【问题描述】:

我正在使用Spring RestTemplateGET request 发送到第三方服务。它返回巨大的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": [
       "...",
       "..."
   ]
}

我有一堂课:

public class SomeModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long entity1;
    private String entity2;    
}

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

【问题讨论】:

    标签: json spring get resttemplate spring-web


    【解决方案1】:

    如果您使用的是 Jackson,您可以使用 @JsonIgnoreProperties(ignoreUnknown = true) 注释您的模型类,如下所示:

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class PosterDishModel implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        private Long entity1;
        private String entity2;    
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 2021-04-23
      • 2021-09-18
      相关资源
      最近更新 更多