どのように動的にジャクソンを使用してサブオブジェクトにキー値のJSON配列をマッピングするには?

カーマゲドン:

我々はJSON構造を持っていると言うことのようになります。

{
 "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;(私たちはに基づいて地図への切り替えが、それはどちらかの仕事をしていないもう一つの答え -動作しません)

私たちの目標は、ダイナミック、属性のないハードコーディングされたリストの属性に保つことです。

これはどのようにある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"])
デッドプール :

対応するMessageJSONが間違った形式である上に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;
  ....
  }

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=181486&siteId=1