我正在尝试使用 Rest Template 将 JSON 绑定(bind)到 POJO。
想象一下有一个 SpaceX
类和a Rocket
类,而SpaceX
类有一个 List<Rocket>
属性。我用@JsonProperty
注释让 Rest 模板在 Rocket
中绑定(bind)“Rocket ID”和“name”自动对象。
我的 JSON 文件以数组开头,如下所示:
[
{
"Rocket ID": "1",
"name": "A"
},
{
"Rocket ID": "2",
"name": "B"
}
]
我能够使用 JSON 文件并填充 List<Rocket>
像这样手动:
public <T> List<T> createObjectsFromJSON(Class<T[]> responseType) {
ResponseEntity<T[]> responseEntity = restTemplate.exchange(URL, HttpMethod.GET, request, responseType);
T[] objects = responseEntity.getBody();
List<T> list = Arrays.asList(objects);
return list;
}
但我想创建一个SpaceX
对象并让 Rest Template 填写 List<Rocket>
自动地。
我无法理解如何做到这一点的答案。我无法告诉 Rest 模板通过 @JsonProperty
绑定(bind)列表,因为没有名字。
最佳答案
如果您无法更改 JSON 结构,则必须编写自定义序列化和反序列化逻辑。您可以使用@JsonCreator和@JsonValue注释:
The @JsonCreator annotation is used to tune the constructor/factory used in deserialization. It’s very helpful when we need to deserialize some JSON that doesn’t exactly match the target entity we need to get.
@JsonValue indicates a single method that should be used to serialize the entire instance.
或者@JsonSerialize和@JsonDeserialize:
@JsonSerialize is used to indicate a custom serializer will be used to marshall the entity.
@JsonDeserialize is used to indicate the use of a custom deserializer.
本文包含更多详细信息和示例:http://www.baeldung.com/jackson-annotations
关于java - Rest 模板与根数组绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48992144/