使用 Jackson 将扁平化的 JSON 反序列化为 Java 对象

Deserializing flattened JSON to Java Object using Jackson

所以我目前正在使用 Jackson 将 JSON 反序列化为复杂的 java 对象。一切正常,但我也有一些字段,例如:

{
  "foo.bar.baz":"qux"
}

对应于 java 个对象,例如:

class Foo {
    AnotherClass bar;
}

class AnotherClass {
    String baz;
}

杰克逊无法弄清楚这些点对应于内部对象。有没有办法让 Jackson 能够反序列化甚至在扁平字段上,例如我示例中的字段?

No Jackson JSON 库不会将此检测为不同的对象级别。您可以改用它:

{
  "foo": {
       "bar": {
            "baz":"qux"
        }
  }
}

你必须创建:

  • Class 包含 FooClass
  • 类型的 "foo" 的包装器Class
  • Class FooClass 包含 "bar" 类型 BarClass
  • Class BarClass 包含 "baz" 类型 String

您可以使用 @JsonUnwrapped:

来做类似的事情
public class Wrapper {
  @JsonUnwrapped(prefix="foo.bar.")
  public AnotherClass foo; // name not used for property in JSON
}

public class AnotherClass {
   String baz;
}
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();
                }
            }
        }
    }
}