开发者

custom converter in XStream

I am using XStream to serialize my Objects to XML format. The formatted xml that I get is as below: node1, node2, node 3 are attributes of pojo,DetailDollars

I have开发者_C百科 requirement where in I have to calucluate a percentage, for example 100/ 25 and add the new node to the existing ones. So, the final output should be :

<DetailDollars>
    <node1>100 </node1> 
    <node2>25</node2> 
    <node3>10</node3> 
</DetailDollars>

I wrote a custom converter and registered to my xstream object.

public void marshal(..){
         writer.startNode("node4");         
         writer.setValue(getNode1()/ getnode2() );
         writer.endNode();
}

But, the xml stream I get has only the new node:

<DetailDollars> 
    <node4>4</node4>
</DetailDollars>

I am not sure which xstream api would get me the desired format. could you please help me with this .


Here is the converter you need:

public class DetailDollarsConverter extends ReflectionConverter {

public DetailDollarsConverter(Mapper mapper,
        ReflectionProvider reflectionProvider) {
    super(mapper, reflectionProvider);
}

@Override
public void marshal(Object obj, HierarchicalStreamWriter writer,
        MarshallingContext context) {
    super.marshal(obj,writer,context);

    DetailDollars dl = (DetailDollars) obj;

    writer.startNode("node4");
    writer.setValue(Double.toString(dl.getNode1() / dl.getNode2()));
    writer.endNode();
}

@Override
public Object unmarshal(HierarchicalStreamReader reader,
        UnmarshallingContext context) {
    return super.unmarshal(reader,context);
}

@SuppressWarnings("unchecked")
@Override
public boolean canConvert(Class clazz) {
    return clazz.equals(DetailDollars.class);
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜