新建User类
@XmlRootElement(name="User")
public class User {
private int id;
private String username;
private String nickname;
private String password;
private Address address;
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getNickname() {
return nickname;
}
public String getPassword() {
return password;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void setPassword(String password) {
this.password = password;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
测试类:
public class marshaller {
public static void main(String[] args) {
try {
JAXBContext jaxbContent = JAXBContext.newInstance(User.class);
Marshaller mar = jaxbContent.createMarshaller();
User u = new User();
u.setId(1);
u.setUsername("xuwei");
u.setNickname("徐伟");
u.setPassword("123456");
Address address = new Address();
address.setAddress("江西省");
u.setAddress(address);
mar.marshal(u, System.out);
String unmarStr = "
江西省1徐伟123456xuwei";
Unmarshaller unmar = jaxbContent.createUnmarshaller();
StringReader reader = new StringReader(unmarStr);
User us = (User) unmar.unmarshal(reader);
System.out.println(us.getNickname());
Address uaddr = us.getAddress();
System.out.println(uaddr.getAddress());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}