Jacksonparser解析器问题:无法从START_ARRAY标记中反序列化<object>的实例

时间:2016-04-05 19:03:19

标签: java json jackson

JSON的片段如下:

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

                "Precautions such as the follow"
            ]}

正如您所看到的,这是字符串和对象的混合,我遇到了#34;无法从START_ARRAY令牌中反序列化com.example.json.Paragraph的实例&#34;

无论如何?

我的课程定义如下所示,内容对象适用于&#39; stylecode&#39;和&#39;内容&#39;属性。

public class Paragraph {

    private String contentStr;    

    private Content content;

Content对象如下所示,

public class Content {  

    private String styleCode;

    private String content;

1 个答案:

答案 0 :(得分:1)

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

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片段对其进行了测试,适用于它。