【发布时间】:2016-11-22 19:41:29
【问题描述】:
假设我有这样的对象
{
first: "value",
second: "value",
third: {
first: "first value third",
second: "second value third",
fourth: {
first: "second nested object",
second: "second nested object"
},
fifth: {
first: "another second nested object",
second: "another second nested object"
}
},
sixth: {
first: "value",
second: "value"
}
}
我正在使用 RestTemplate 类从 URL 中获取 json,如下所示:
RestTemplate rest = new RestTemplate();
String result = rest.getForObject(ENDPOINT_URL, String.class);
之后我想使用杰克逊对象映射器将 json 字符串转换为对象
import com.fasterxml.jackson.databind.ObjectMapper
将实体类作为第二个参数传递
ObjectMapper mapper = new ObjectMapper();
object = mapper.readValue(result, ExampleJson.class);
问题是我应该如何编写 ExampleJson 实体来处理显示的 json?我尝试过这样的课程,但似乎不起作用。
public class ExampleJson {
private String first;
private String second;
private Third third;
private Sixth sixth;
// Getters && Setters
public static class Third {
private String first;
private String second;
private Fourth fourth
private Fifth fifth
// Getters && Setters
private Fourth {
private String first;
private String second;
// Getters && Setters
}
private Fifth {
private String first;
private String second;
// Getters && Setters
}
}
public static class Sixth {
private String first;
private String second;
// Getters && Setters
}
}
我遇到了这样的异常:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "fourth"
【问题讨论】:
-
对象是否始终采用相同的格式,还是可以动态更改?
-
内部类需要是静态的或以其他方式实例化它们,例如没有零参数构造函数或任何注释。 cowtowncoder.com/blog/archives/2010/08/entry_411.html
-
用
@JsonIgnoreProperties(ignoreUnknown = true)注释你要反序列化的类 -
通过将“第四”和“第五”类设为静态来修复它们。
-
@J.West 有一种情况,json不能有我上面提到的所有字段。
标签: java spring parsing jackson resttemplate