How to parse XML with repeated XML tags into a POJO using Jackson?

跟風遠走 提交于 2019-12-07 23:54:35

问题


I am having issues with parsing this XML into a POJO using Jackson. I have read all the previous descriptions on making classes to de-serialise the XML into POJOS but I keep getting either Null pointers or not END of element warnings. I am extremely confused and any help is much appreciated.

The input xml is

                 <row>               
                    <entry align="right" valign="top">20</entry>
                    <entry align="right" valign="top">1A</entry>
                    <entry valign="top">SData</entry>
                    <entry align="center" valign="top">2</entry>
                    <entry valign="top">binary</entry>
                    <entry valign="top">Java enterprise</entry>
                </row>

The code I am using is;

static void testSmallXml(){
    String big = null;
    try
    {
        big = readFileToString("other/testXML/NewFile.xml");
    } catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    XmlMapper xmlMapper = new XmlMapper();


    String small = big.substring(big.lastIndexOf("<row>"), big.lastIndexOf("</row>")+8);

        try
        {
            rows in =  xmlMapper.readValue(small, rows.class);
            System.out.println(in.entries[0].value);
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           

        System.out.println(small);

}

and my POJO classes are

@JacksonXmlRootElement(localName = "row")
@JsonIgnoreProperties(ignoreUnknown = true)
public static class rows{   
    @JacksonXmlProperty(localName = "entry")
    public entry[] entries;
}

@JacksonXmlRootElement(localName = "entry")
@JsonIgnoreProperties(ignoreUnknown = true)
public static class entry{  

    @JacksonXmlProperty(isAttribute = true)
    private String align;

    @JacksonXmlProperty(isAttribute = true)
    private String valign;

    @JacksonXmlText
    public String value;

}

I keep getting a Null pointer exception for
rows["entry"]->Object[][2])


回答1:


Try this:

@JacksonXmlRootElement(localName = "row")
public static class rows {
    @JacksonXmlElementWrapper(useWrapping=false)
    @JacksonXmlProperty(localName = "entry")
    public entry[] entries;
}

public static class entry {
    @JacksonXmlProperty(isAttribute = true)
    private String align;

    @JacksonXmlProperty(isAttribute = true)
    private String valign;

    @JacksonXmlText
    public String value;
}


来源:https://stackoverflow.com/questions/40711673/how-to-parse-xml-with-repeated-xml-tags-into-a-pojo-using-jackson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!