使用JsonAnySetter注解将具有无限嵌套结构的动态JSON对象映射到Map中。

huangapple go评论61阅读模式
英文:

Mapping dynamic JSON object with unlimited nested structure to Map using JsonAnySetter annotation

问题

我想将 JSON对象 映射到具有自定义结构的 Java 类。
例如:

public class RestAttributesMappingDTO {
    Map<String, Object> details = new LinkedHashMap<>();
    @JsonAnySetter
    void setDetail(String key, Object value) {
        details.put(key, value);
    }
}

如你所见,使用了注解 @JsonAnySetter 进行映射。

对于任何扁平的结构都是可以的。

但是如果我想要映射具有无限(自定义)嵌套结构的对象呢?

例如:

{
    "name": "",
    "age": "",
    "job": [{
         "job1": {  
              "title": "",
              "ZIP": ""                   
         }
    }]
}

会出现递归算法,用于在没有 @JsonAnySetter 的情况下创建映射。

但是否有任何方法可以使用 Jackson 构建这个无限嵌套的映射呢?

英文:

I want to map JSON Object to Java class with custom structure.
For example:

public class RestAttributesMappingDTO {
    Map&lt;String, Object&gt; details = new LinkedHashMap&lt;&gt;();
    @JsonAnySetter
    void setDetail(String key, Object value) {
        details.put(key, value);
    }
}

As you can see, annotation @JsonAnySetter have been used for mapping.

Its ok for any flat structure.

But if I want to map object with unlimited (custom) nested structure?

For example:

{
    name: &quot;&quot;,
    age: &quot;&quot;,
    job: [{
         job1: {  
              title: &quot;&quot;,
              ZIP: &quot;&quot;                   
         }
    }]
}

Arises recursive algorithm of creating map without @JsonAnySetter.

But is there any way to build this unlimited nested map with Jackson?

答案1

得分: 1

默认情况下,Jackson 进行反序列化的操作如下:

  • JSON 对象 反序列化为键为 String 类型的 Map
  • JSON 数组 反序列化为对象或基本类型的 List

在你的示例中,你可以保持现有方式,但需要在运行时进行类型转换和类型检查。另一种选择是使用 com.fasterxml.jackson.databind.JsonNode 类,方法可能如下所示:

void setDetail(String key, JsonNode value)

但你甚至可以跳过这个方法和 @JsonAnySetter 注解,直接在类中使用它:

public class RestAttributesMappingDTO {
    private JsonNode details;
    //getters, setters
}

JsonNode 允许遍历 键-值 对。

参考一些其他相关的问题:

英文:

Jackson by default deserialises:

  • JSON Object to Map where keys are String-s.
  • JSON Array to List of objects or primitives.

In your example, you can keep like it is but it would need casting and checking types in runtime. Other option is to use com.fasterxml.jackson.databind.JsonNode class and method could look like:

void setDetail(String key, JsonNode value)

But you can even skip this method and @JsonAnySetter annotation and use it in class directly:

public class RestAttributesMappingDTO {
    private JsonNode details;
    //getters, setters
}

JsonNode allows to iterate over key-value pairs.

See some other related questions:

huangapple
  • 本文由 发表于 2020年9月23日 22:40:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64030400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定