如何使用Jackson动态地将键值的JSON数组映射到子对象?

Car*_*don 5 java json jackson spring-boot jackson2

假设我们有一个如下所示的JSON结构:

{
 "field1": "val1",
 "field2": "v2",
 "f3": "v3",
 "f4": "v4",
 "arrayOfStuff": [
  {
   "f5": "v5",
   ....
   "f10": "v10"
  }
 ],
 "attributes": [
  {"att1": "att1"},
  {"att2": "attr2"},
  {"att3": "att3"}
 ],
 "options": [
  "ignoreMismatchFile"
 ]
}
Run Code Online (Sandbox Code Playgroud)

我们匹配的java类看起来像:

public class Message {
   @IsUniqueId
   private String field1; //
   private String field2;
   private String field3;
   private String field4;
   private List<AnotherObject> f5;
   @JsonProperty("attributes")
   private LinkedHashMap<String, String> attributes;
   private List<String> options;
   ....
}
Run Code Online (Sandbox Code Playgroud)

解析代码如下所示:

protected Message loadSavedMessageAsMessageObject(String path) throws IOException {
    File file = ResourceUtils.getFile(path);
    if (file.exists()) {
        ObjectMapper mapper = this.getObjectMapper();
        return mapper.readValue(file, Message.class);
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

我们尝试了不同的方法来完成这个,最初我们试图将属性作为private List<MessageAttribute> attributes;但是也没有用(我们根据另一个答案切换到地图- 不起作用)

我们的目标是使属性保持动态,而不是硬编码的属性列表.

这就是MessageAttribute班级的样子:

public class MessageAttribute {
    private String key;
    private String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

我们目前获得的例外是:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap` out of START_OBJECT token
at [Source: (File); line: 32, column: 3] (through reference chain: com.org.Message["attributes"])
Run Code Online (Sandbox Code Playgroud)

Dea*_*ool 3

与上面的 JSON对应的MessagePOJO 格式错误,我做了一些更改attributes应该是List of Map并且列表AnotherObject应该指向 arrayOfStuff

public class Message {
 @IsUniqueId
 private String field1; //
 private String field2;
 private String field3;
 private String field4;
 private List<AnotherObject> arrayOfStuff;  //or you can have List<Map<String,String>> arrayOfStuff
 @JsonProperty("attributes")
 private List<LinkedHashMap<String, String>> attributes; // this is list of map objects
 private List<String> options;
  ....
  }
Run Code Online (Sandbox Code Playgroud)