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

微笑、不失礼 提交于 2021-02-05 06:49:05

问题


I have a json field that is string when there's one value:

{ "theField":"oneValue" }

or array when there are multiple values:

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

And then I have my java class that uses com.fasterxml.jackson.annotation.JsonCreator:

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

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

The problem is that the code does not work when the incoming field is string. The exception thrown is:

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

And if I change it to expect string it throws the similar exception against an array...

I'd appreciate any ideas on what should I use instead of @JsonCreator or how to make it work with both types of field

Thanks in advance,
Stan Kilaru


回答1:


Maybe you should try the following:

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


来源:https://stackoverflow.com/questions/36330226/how-to-parse-a-json-field-that-may-be-a-string-and-may-be-an-array-with-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!