Ale*_*sto 5 spring json get resttemplate spring-web
我正在使用Spring RestTemplate
发送GET request
到第三方服务。它返回JSON
代表 a 的巨大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": [
"...",
"..."
]
}
Run Code Online (Sandbox Code Playgroud)
我有一堂课:
public class SomeModel implements Serializable {
private static final long serialVersionUID = 1L;
private Long entity1;
private String entity2;
}
Run Code Online (Sandbox Code Playgroud)
如何将此 JSON 转换为此类的实例数组?
如果您使用 Jackson,您可以使用 来注释您的模型类@JsonIgnoreProperties(ignoreUnknown = true)
,如下所示:
@JsonIgnoreProperties(ignoreUnknown = true)
public class PosterDishModel implements Serializable {
private static final long serialVersionUID = 1L;
private Long entity1;
private String entity2;
}
Run Code Online (Sandbox Code Playgroud)
基本上,它指示 Jackson 丢弃接收到的对象中的任何未知属性。
请注意,这不会阻止整个对象通过网络传输,流量将相同,但您要反序列化的对象将不包含不必要的字段和数据。