如何解析xml像下面与Jackson?

mfpqipee  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(151)

输入xml:

<root>
  <row>
    <foo>foo</foo>
    <bar>bar</bar>
  </row>
  <row>
    <foo>foo2</foo>
    <bar>bar2</bar>
  </row>
  <row>
    <foo>foo3</foo>
    <bar>bar3</bar>
  </row>
</root>

如果我这样解析它:

XmlMapper = new XmlMapper();
Map map = xmlMapper.readValue(decodedXml, Map.class);

结果Map将仅包含最后一行。
如何让它把行解析成一个ArrayList?

jdzmm42g

jdzmm42g1#

我觉得你可以变成

List list = xmlMapper.readValue(decodedXml, List.class)

列表中对象是LinkedHashMap

kqhtkvqz

kqhtkvqz2#

创建两个类:
第一个
对于试验:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import generated.Root; // your package

public class Demo {

    public static void main(String[] args) throws JsonMappingException, JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        XmlMapper xmlMapper = new XmlMapper();

        String xml = "<root>\r\n"
                + "  <row>\r\n"
                + "    <foo>foo</foo>\r\n"
                + "    <bar>bar</bar>\r\n"
                + "  </row>\r\n"
                + "  <row>\r\n"
                + "    <foo>foo2</foo>\r\n"
                + "    <bar>bar2</bar>\r\n"
                + "  </row>\r\n"
                + "  <row>\r\n"
                + "    <foo>foo3</foo>\r\n"
                + "    <bar>bar3</bar>\r\n"
                + "  </row>\r\n"
                + "</root>";
        Root map = xmlMapper.readValue(xml, Root.class);

        System.out.println("value "+ mapper.writeValueAsString(map));

    }

}

结果:

value {"row":[{"foo":"foo","bar":"bar"},{"foo":"foo2","bar":"bar2"},{"foo":"foo3","bar":"bar3"}]}

相关问题