【问题标题】:Deserializing flattened JSON to Java Object using Jackson使用 Jackson 将扁平化的 JSON 反序列化为 Java 对象
【发布时间】:2016-05-17 17:55:12
【问题描述】:

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

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

对应java对象如:

class Foo {
    AnotherClass bar;
}

class AnotherClass {
    String baz;
}

Jackson 无法确定这些点对应于内部对象。有没有办法让 Jackson 能够反序列化,即使在我的示例中的字段等扁平字段上也是如此?

【问题讨论】:

  • "foo.bar.baz" is not 不是有效的 JSON 格式
  • @CMPS: :) 我喜欢你的回答格式也不正确。
  • 不了解实现,但如果您使用 YAML 解析器,您的示例具有您想要的语义。

标签: java serialization jackson deserialization json-deserialization


【解决方案1】:

没有 Jackson JSON 库不会将此检测为不同的对象级别。你可以改用这个:

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

你必须创造:

  • 类 WrapperClass 包含 FooClass 类型的“foo”
  • 类 FooClass 包含类型为 BarClass 的“bar”
  • 类 BarClass 包含字符串类型的“baz”

【讨论】:

    【解决方案2】:

    你可以使用@JsonUnwrapped来做类似的事情:

    public class Wrapper {
      @JsonUnwrapped(prefix="foo.bar.")
      public AnotherClass foo; // name not used for property in JSON
    }
    
    public class AnotherClass {
       String baz;
    }
    

    【讨论】:

      【解决方案3】:
      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();
                      }
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 2014-02-12
        相关资源
        最近更新 更多