引用包:
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <classifier>jdk15</classifier><!--指定jdk版本 --> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency>
然后使用 net.sf.json.xml.XMLSerializer 类进行解析。
比如xml是:
<item> <blog>sanshu.cn</blog> <bukrs>1100</bukrs> <zztid>8840</zztid> <zzbbsyb>6</zzbbsyb> <zfl>102.39</zfl> </item>
我们的实体类是:
public static class ItemDetail { private String blog; private String zfl; private String zzbbsyb; private Long zztid; private String bukrs; //..........getter setter }
转换代码是:
public static void main(String[] args) { XMLSerializer xmlSerializer = new XMLSerializer(); //解析成json JSONObject json = (JSONObject)xmlSerializer.read(xml); //解析成实体类 ItemDetail p =(ItemDetail)JSONObject.toBean(json, ItemDetail.class); System.out.println(p.getBlog()); }
最后输出结果: