杰克逊解析器解析器问题:无法反序列化 <OBJECT> out of START_ARRAY 令牌的实例



JSON的片段如下:

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

正如您所看到的,这是字符串和对象的混合,我遇到了"无法反序列化com.example.json的实例。START_ARAY令牌中的段落"

不管怎么说?

我的类定义如下所示,Content对象用于"stylecode"one_answers"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片段对其进行了测试,适用于它。

相关内容

最新更新