UPDATE
爲跟進這樣的:我能做到這樣?如果xml被返回 as 4 ..... 如果我正在構造一個Person對象,我相信這會窒息。 我可以只綁定我想要的xml元素嗎?如果是的,我該怎麼做 那。
輸入:
如下您可以映射此XML。XML
<?xml version="1.0" encoding="UTF-8"?>
<Persons>
<NumberOfPersons>2</NumberOfPersons>
<Person>
<Name>Jane</Name>
<Age>40</Age>
</Person>
<Person>
<Name>John</Name>
<Age>50</Age>
</Person>
</Persons>
人
package forum7177628;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Persons")
@XmlAccessorType(XmlAccessType.FIELD)
public class Persons {
@XmlElement(name="Person")
private List<Person> people;
}
人
package forum7177628;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
@XmlElement(name="Name")
private String name;
@XmlElement(name="Age")
private int age;
}
演示
package forum7177628;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Persons.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Persons persons = (Persons) unmarshaller.unmarshal(new File("src/forum7177628/input.xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(persons, System.out);
}
}
輸出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Persons>
<Person>
<Name>Jane</Name>
<Age>40</Age>
</Person>
<Person>
<Name>John</Name>
<Age>50</Age>
</Person>
</Persons>
原來的答案
下面是調用使用Java SE API,其中包括JAXB RESTful服務的一個示例:
String uri =
"http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
(Customer) jc.createUnmarshaller().unmarshal(xml);
connection.disconnect();
欲瞭解更多信息:
如果你可以調用服務,並得到回JSON相反,GSON /傑克遜蜜蜂比JAXB更容易,因爲你並不需要在模型上標註對象 – Kevin
嗨凱文,我有一個外部REST服務我想從Web應用程序調用它。什麼是最好的方式來做到這一點? REST服務返回JSON格式作爲響應。你說這很容易處理JSON響應。你能解釋一下嗎? – Jignesh