如何用Jackson解析可能是字符串也可能是数组的json字段 [英] How to parse a json field that may be a string and may be an array with Jackson

查看:29
本文介绍了如何用Jackson解析可能是字符串也可能是数组的json字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 json 字段,当有一个值时它是字符串:

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" ] }

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

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...

我很感激关于我应该使用什么而不是@JsonCreator 或如何使其与两种类型的字段一起使用的任何想法

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

这篇关于如何用Jackson解析可能是字符串也可能是数组的json字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆