1 回答

TA貢獻1831條經驗 獲得超4個贊
您的問題是由于濫用 xml 注釋造成的。您可以Tuple2通過使用 注釋將 a 定義為 xml 根元素@XmlRootElement,并通過使用 注釋 get 方法將其字段定義為 xml 屬性@XmlAttribute。翻譯過來就是:
<tuple2 first="first_attributes_vale" second="second_attributes_value" />
現在,兩個字段都是 類型,通過使用 注釋該類Coords來將其聲明為另一個 xml 元素,并且其字段為 xml 屬性。當序列化為 xml 時,它將是:Coords@XmlRootElementCoords
<coords x="value" y="value" />
序列化時會出現問題Tuple2。它的字段應該是 xml 屬性,但實際上Coords是另一個 xml 元素。Xml 屬性不能包含嵌套元素,只能包含值。
解決方案
根據您的需要,您可以通過兩種不同的方式解決這個問題。不過,我不推薦第二種方法,因為它很奇怪(即使它有效)并且會在客戶端產生額外的工作(請參閱下面的解釋)。
第一種方法
使用注釋來注釋getFirst()和getSecond()方法@XmlElement。
package model;
import static javax.xml.bind.annotation.XmlAccessType.NONE;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(NONE)
public class Tuple2 {
private Coords c1;
private Coords c2;
public Tuple2(Coords c1, Coords c2) {
this.c1 = c1;
this.c2 = c2;
}
public Tuple2() {
c1 = new Coords(0, 0);
c2 = new Coords(0, 0);
}
@XmlElement
public Coords getFirst() {
return this.c1;
}
@XmlElement
public Coords getSecond() {
return this.c2;
}
}
這將產生如下所示的結果:
<tuple2>
<first x="2" y="4"/>
<second x="12" y="12"/>
</tuple2>
第二種方法
這是解決這個問題的奇怪方法。它可以工作,但會在客戶端產生額外的工作,因為 的值Coords被編碼為字符串值,并且需要在接收端進行解析。
getFirst()將和方法的返回類型更改getSecond()為String并覆蓋toString()的方法Coords。
package model;
import static javax.xml.bind.annotation.XmlAccessType.NONE;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(NONE)
public class Tuple2 {
private Coords c1;
private Coords c2;
public Tuple2(Coords c1, Coords c2) {
this.c1 = c1;
this.c2 = c2;
}
public Tuple2() {
c1 = new Coords(0, 0);
c2 = new Coords(0, 0);
}
@XmlAttribute
public String getFirst() {
return this.c1.toString();
}
@XmlAttribute
public String getSecond() {
return this.c2.toString();
}
}
重寫toString()以下方法Coords:
package model;
import static javax.xml.bind.annotation.XmlAccessType.NONE;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(NONE)
public class Coords {
@XmlAttribute private int x;
@XmlAttribute private int y;
public Coords(final int x, final int y) {
this.x = x;
this.y = y;
}
public Coords() {
this.x = 0;
this.y = 0;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Coords [x=");
builder.append(x);
builder.append(", y=");
builder.append(y);
builder.append("]");
return builder.toString();
}
}
這將產生與此類似的結果:
<tuple2 first="Coords [x=2, y=4]" second="Coords [x=12, y=12]"/>
屬性first和的值second將是任何方法返回toString()的值Coords。
添加回答
舉報