像GSON一样的SOAP解析器?

时间:2012-07-09 02:42:07

标签: java json soap jaxb xml-parsing

是否有像GSON这样的免费开源SOAP解析器会自动将解析后的数据映射到相应的bean?如果没有,你能推荐一个好的但是免费的开源SOAP解析器吗?

先谢谢!

1 个答案:

答案 0 :(得分:4)

您可以尝试JAXB(Java Architecture for XML Binding)API。看看样本:

Xml文件

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Child>
        <foo>10</foo>
    </Child>
    <Child>
        <foo>20</foo>
    </Child>
</Root>

Java POJO代表XML架构

@XmlRootElement(name="Root")
class Bar{
  private List<Foo> list=new ArrayList();   
  @XmlElement(name="Child")
  public List<Foo> getList(){ return list;}
}
class Foo{
    private Integer foo;
    public Foo(){ foo=0;}
    public Foo(Integer foo) { this.foo=foo;}
    public Integer getFoo() { return foo; }
    public void setFoo(Integer foo){ this.foo=foo;}
}

从XML读取Java对象

JAXBContext context=JAXBContext.newInstance(Bar.class);
Unmarshaller um=context.createUnmarshaller();

Bar bar=(Bar)um.unmarshal(new File("x:\\path\\xmldoc.xml")); // you may specify the URL too.

System.out.println(bar.getList());
for(Foo c:bar.getList()){
    System.out.println(c.getFoo());
}