gpt4 book ai didi

java - Jacksonparser解析器问题: Can not deserialize instance of out of START_ARRAY token
转载 作者:行者123 更新时间:2023-12-01 10:06:22 25 4
gpt4 key购买 nike

JSON 片段如下:

"text": {"paragraph": [
"For use in manufacturing only.",
[
{
"styleCode": "bold",
"content": "CAUTION:"
},
"Certain components of machine feeds"
],

"Precautions such as the follow"
]}

如您所见,这是字符串和对象的混合,我遇到“无法从 START_ARRAY token 中反序列化 com.example.json.Paragraph 的实例”

无论如何?

我的类定义如下所示,Content对象用于“stylecode”和“content”属性。

public class Paragraph {

private String contentStr;

private Content content;

Content对象如下所示,

public class Content {  

private String styleCode;

private String content;

最佳答案

我认为你的对象应该是这样的-内容类别

public class Content {
private String styleCode;
private String content;
private String data;

//Getter Setter Methods
}

段落类

public class Paragraph {
private List<Content> contentList;

//Getter Setter Method
}

反序列化器类应该是

public class ParagraphDeserializer extends JsonDeserializer<Paragraph> {

@Override
public Paragraph deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);

JsonNode text = node.get("text");
JsonNode paragraphs = text.get("paragraph");

List<Content> contentList = new ArrayList<Content>();

for(int i = 0; i < paragraphs.size(); i++) {

JsonNode p = paragraphs.get(i);

Content c = new Content();

String data = "", styleCode = "", content = "";

try {
data = p.textValue();
} catch(Exception ignore) {
}

if(data == null) {
for(int j = 0; j < p.size(); j++) {
JsonNode o = p.get(j);

try {
data = o.textValue();

if(data != null) {
c.setData(data);
}
} catch(Exception ignore) {
}

if(data == null) {
styleCode = o.get("styleCode").textValue();
content = o.get("content").textValue();
}
}
} else {
c.setData(data);
}

c.setContent(content);
c.setStyleCode(styleCode);

contentList.add(c);
}

Paragraph p = new Paragraph();
p.setContentList(contentList);
return p;
}
}

我已经针对您给定的 json 片段对其进行了测试,可以正常工作。

关于java - Jacksonparser解析器问题: Can not deserialize instance of <OBJECT> out of START_ARRAY token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36434916/

25 4 0