代码之家  ›  专栏  ›  技术社区  ›  Carmageddon

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

  •  5
  • Carmageddon  · 技术社区  · 7 年前

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

    我们匹配的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;
       ....
    }
    

    解析代码如下所示:

    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;
    }
    

    private List<MessageAttribute> attributes; 但这也不起作用(我们根据 Another answer

    我们的目标是让属性保持一个动态的,而不是硬编码的属性列表。

    这就是 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;
        }
    }
    

    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"])
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Ryuzaki L    7 年前

    符合的 Message 以上JSON的POJO格式错误,我做了几处更改 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;
      ....
      }