簡體   English   中英

如何用Jackson解析可能是字符串也可能是數組的json字段

[英]How to parse a json field that may be a string and may be an array with Jackson

我有一個 json 字段,當有一個值時它是字符串:

{ "theField":"oneValue" }

或數組,當有多個值時:

{ "theField": [ "firstValue", "secondValue" ] }

然后我有使用 com.fasterxml.jackson.annotation.JsonCreator 的 java 類:

public class TheClass { 
    private final List<String> theField;

    @JsonCreator
    public TheClass(@JsonProperty("theField") List<String> theField) {
        this.theField = theField;
    }
}

問題是當傳入字段是字符串時代碼不起作用。 拋出的異常是:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

如果我將其更改為期望字符串,它會針對數組拋出類似的異常...

我很感激關於我應該使用什么而不是@JsonCreator 或如何使其適用於這兩種類型的字段的任何想法

提前致謝,
斯坦·基拉魯

也許您應該嘗試以下操作:

public class TheClass { 
    private final List<String> theField;

    @JsonCreator
    public TheClass(@JsonProperty("theField") Object theField) {
        if (theField instanceof ArrayList) {
            this.theField = theField;
        } else {
            this.theField = new ArrayList<String>();
            this.theField.add(theField);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM