gpt4 book ai didi

java - 如何使用 Jackson 解析可能是字符串也可能是数组的 json 字段

转载 作者:行者123 更新时间:2023-11-30 10:46:54 24 4
gpt4 key购买 nike

我有一个 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);
}
}
}

关于java - 如何使用 Jackson 解析可能是字符串也可能是数组的 json 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36330226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com