springboot将webservice数据解析成list
时间: 2023-11-26 11:04:34 浏览: 96
可以使用JAXB来将WebService返回的XML数据解析成List。具体实现可以参考以下代码:
```java
@WebService
public class MyWebService {
@WebMethod
public List<MyObject> getData() {
List<MyObject> result = new ArrayList<>();
// 调用WebService获取数据
String xmlData = callWebService();
try {
// 使用JAXB将XML解析成Java对象
JAXBContext jaxbContext = JAXBContext.newInstance(MyObject.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<MyObjectList> element = unmarshaller.unmarshal(new StreamSource(new StringReader(xmlData)), MyObjectList.class);
MyObjectList myObjectList = element.getValue();
result = myObjectList.getMyObjects();
} catch (JAXBException e) {
e.printStackTrace();
}
return result;
}
}
@XmlRootElement(name = "MyObjectList")
@XmlAccessorType(XmlAccessType.FIELD)
class MyObjectList {
@XmlElement(name = "MyObject")
private List<MyObject> myObjects;
public List<MyObject> getMyObjects() {
return myObjects;
}
public void setMyObjects(List<MyObject> myObjects) {
this.myObjects = myObjects;
}
}
@XmlRootElement(name = "MyObject")
@XmlAccessorType(XmlAccessType.FIELD)
class MyObject {
@XmlElement(name = "Id")
private String id;
@XmlElement(name = "Name")
private String name;
@XmlElement(name = "Age")
private int age;
// 省略getter和setter方法
}
```
阅读全文