Marshalling an object that has object fields
Not sure if the title makes any sense. I have an object that I want to marshal using JAXB that looks like this:
@XmlRootElement(name = "subscriptionRequest")
public class RegistrationRequest {
开发者_如何学Go private Long id;
private RegistrationSource registrationSource;
}
The RegistrationSource object:
public class RegistrationSource {
private Integer id;
private String code;
}
I want to create an xml that has the following layout:
<subscriptionRequest registrationSource="0002">
...
</subscriptionRequest>
where the registrationSource attribute value is the code field value from the RegistrationSource object.
What xml annotations do I need to use?
@XmlAttribute
on registrationSource
, @XmlValue
on code
. Note that in this case you also should have @XmlTransient
on other fields of RegistrationSource
, such as id
EDIT: This works:
@XmlRootElement(name = "subscriptionRequest")
public class RegistrationRequest {
private Long id;
private RegistrationSource registrationSource;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
@XmlAttribute
public RegistrationSource getRegistrationSource() { return registrationSource; }
public void setRegistrationSource(RegistrationSource registrationSource)
{
this.registrationSource = registrationSource;
}
}
-
public class RegistrationSource {
private Integer id;
private String code;
@XmlTransient
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
@XmlValue
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
}
If you want to generate this class automatically using some tools , then try this - Generate xsd from your xml using tools like Trang, and then generate java file from xsd using jaxb. Life would be much simpler :)
The lame approach would be to add something like
@XmlAttribute(name = "registrationSource")
private String getCode() {
return registrationSource.code;
}
to your RegistrationSource
-- but there must be a more elegant way...
精彩评论