如果我的 REST 服务返回以下 JSON 结构:
{
"foo" : {
"id" : "baz"
}
"qux" : {
"id" : "toto"
}
}
对我来说,它看起来像一个 map 结构。我不知道如何使用 Spring Boot(通过 Jackson)阅读此内容。
我已经定义了我的 JSON 绑定(bind)类,如下所示:
public class Foos {
private Map<String, Foo> fooInstances;
private void setFooInstances(Map<String, Foo> fooInstances) {
this.fooInstances = fooInstances;
}
private Map<String, Foo> getFooInstances() {
return fooInstances;
}
}
Foo 实例如下所示:
public class Foo {
private String id;
private void setId(String id) {
this.id = id;
}
private String getId() {
return id;
}
}
发出请求的 spring 代码如下:
RestTemplate template = new RestTemplate();
ResponseEntity<Foos> responseEntity = (ResponseEntity<Foos>) template.getForEntity(serviceEndpointURL, Foos.class);
我最初遇到了 START_OBJECT 错误,我通过使用相应的 map 创建 Foos 类来修复该错误,现在我没有收到错误。相反,我得到了一个填充的 ResponseEntity,带有“Foos”实例,但 map 为空。知道我做错了什么吗?
最佳答案
像这样修改你的 Foos 类
public class Foos {
@JsonIgnore
private Map<String, Object> properties = new HashMap<String, Object>();
@JsonAnyGetter
public Map<String, Object> getProperties() {
return this.properties;
}
@JsonAnySetter
public void setProperty(String name, Object value) {
this.properties.put(name, value);
}
}
您可以从 map 中从 Object
类型转换为 Foo
。
如果您有任何疑问,请告诉我!
关于java - 通过spring boot读取JSON映射结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42518270/