所以我目前正在使用Jackson将JSON反序列化为复杂的java对象。一切都运作良好,但我也有一些领域,如:
{
"foo.bar.baz":"qux"
}
对应于java对象,例如:
class Foo {
AnotherClass bar;
}
class AnotherClass {
String baz;
}
杰克逊无法弄清楚这些点对应于内部物体。有没有办法让杰克逊能够在我的例子中的平场上进行反序列化?
答案 0 :(得分:0)
没有Jackson JSON库不会将此检测为不同的对象级别。您可以改为使用它:
{
"foo": {
"bar": {
"baz":"qux"
}
}
}
你必须创建:
答案 1 :(得分:0)
您可以使用@JsonUnwrapped
:
public class Wrapper {
@JsonUnwrapped(prefix="foo.bar.")
public AnotherClass foo; // name not used for property in JSON
}
public class AnotherClass {
String baz;
}
答案 2 :(得分:0)
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(jsonString);
Iterator<String> iterator = root.fieldNames();
while (iterator.hasNext()) {
String fieldName = iterator.next();
if (fieldName.contains(".")) {
String[] items = fieldName.split("\\.");
if (items[0].equals("foo")) {
Foo foo = new Foo();
if (items[1].equals("bar")) {
AnotherClass bar = new AnotherClass();
foo.bar = bar;
if (items[2].equals("baz")) {
bar.baz = root.get(fieldName).asText();
}
}
}
}
}