2016-08-11 55 views
3

我使用Spring RestTemplateGET request发送给第三方服务。它返回巨大的JSON,代表list of some entities。但是每个实体都非常庞大,包含大量不必要的数据。我只需要从每个实体获得三个字段。我如何建立我的模型来实现它?例如,如果我们有这样的JSON使用RestTemplate部分检索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转换为该类的实例的阵列?

回答

2

如果您使用杰克逊,你可以用@JsonIgnoreProperties(ignoreUnknown = true)注解你的模型类,因为这样的:

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

    private static final long serialVersionUID = 1L; 

    private Long entity1; 
    private String entity2;  
} 

基本上,它指示杰克逊丢弃在接收对象中的任何属性未知。

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

+0

非常感谢,它帮助! :) – Alesto