2015-11-22 23 views
1

我有以下問題,我不知道如何解決這個問題。如何忽略字段名,而編組/解組Java對象

我有一個基於通用接口的不同類型的點列表。 我正在使用Java XStream來編組和解組這些類。

public static void main(String[] args) { 

    List<IPoint> listOfPoint = new ArrayList<IPoint>(); 
    listOfPoint.add(new PointTypeA(0.1)); 
    listOfPoint.add(new PointTypeB(0.2)); 
    listOfPoint.add(new PointTypeA(0.3)); 
    PointSet ps = new PointSet(1, listOfPoint); 

    XStream xstream = new XStream(new StaxDriver()); 
    xstream.processAnnotations(PointTypeA.class); 
    xstream.processAnnotations(PointTypeB.class); 
    xstream.processAnnotations(PointSet.class); 

    String xml = xstream.toXML(ps); 
    System.out.println(xml); 
} 

當我打印我的XML格式的對象,我得到以下結果:以上但

<set id="1"> 
    <typeA> 
    <xCoordinate>0.1</xCoordinate> 
    </typeA> 
    <typeB> 
    <xCoordinate>0.2</xCoordinate> 
    </typeB> 
    <typeA> 
    <xCoordinate>0.3</xCoordinate> 
    </typeA> 
</set> 

,而不是結果,我想有以下輸出:

<set id="1"> 
    <typeA>0.1</typeA> 
    <typeB>0.2</typeB> 
    <typeA>0.3</typeA> 
</set> 

我想要的不是像<xCoordinate>這樣的標籤,但我希望它們的值存儲在classname的標籤下。 我不想忽略xCoordinate字段的值,但我想要有一個「內聯值」。 可以這樣做嗎? 我試過轉換器沒有成功,我不知道如何解決這個問題。

我的類別是:

public interface IPoint { 

    int getSomeInformation(); 
} 

@XStreamAlias("set") 
public class PointSet { 

    @XStreamAsAttribute 
    private int id; 

    @XStreamImplicit 
    private List<IPoint> points; 

    public PointSet(int id, List<IPoint> points) { 
     super(); 
     this.id = id; 
     this.points = points; 
    } 
} 

@XStreamAlias("typeA") 
public class PointTypeA implements IPoint { 

    private double xCoordinate; 

    public PointTypeA(double d) { 
     super(); 
     this.xCoordinate = d; 
    } 
} 

@XStreamAlias("typeB") 
public class PointTypeB implements IPoint { 

    private double xCoordinate; 

    public PointTypeB(double d) { 
     super(); 
     this.xCoordinate = d; 
    } 
} 

,如果你能幫幫我。 謝謝。

+0

我不知道XStream是如何工作的,但通常在Java中使用關鍵字「transient」來指示變量不會自動存儲/檢索。 不要把它與「易失性」順便混淆起來,這表明變量是緩存方面的通讀和直寫。 – JayC667

回答

0

轉換器爲您的點類是相當簡單的。

public static class CoordConverter implements Converter 
{ 
    public boolean canConvert(Class clazz) 
    { 
     return PointTypeA.class == clazz; 
    } 

    public void marshal(Object object, HierarchicalStreamWriter hsw, MarshallingContext mc) 
    { 
     PointTypeA obj = (PointTypeA) object; 
     hsw.setValue(String.valueOf(obj.xCoordinate)); 
    } 

    public Object unmarshal(HierarchicalStreamReader hsr, UnmarshallingContext uc) 
    { 
     double val = Double.parseDouble(hsr.getValue()); 
     PointTypeA obj = new PointTypeA(val); 
     return obj; 
    } 
} 

您可以

xstream.registerConverter(new CoordConverter()); 

當然其註冊,該轉換器的有效期爲PointTypeA類,但你可以很容易地將以上的其他類的代碼,你需要和/或寫更多的通用版本。