简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM