xml serialization - How to conditionally serialize a field (attribute) using XStream -


i using xstream serializing , de-serializing object. example, class named rating defined follows:

public class rating {    string id;   int score;   int confidence;    // constructors here... } 

however, in class, variable confidence optional.

so, when confidence value known (not 0), xml representation of rating object should like:

<rating> <id>0123</id> <score>5</score> <confidence>10</confidence> </rating> 

however, when confidence unknown (the default value 0), confidence attribute should omitted xml representation:

<rating> <id>0123</id> <score>5</score> </rating> 

could tell me how conditionally serialize field using xstream?

one option write converter.

here's 1 wrote you:

import com.thoughtworks.xstream.converters.converter; import com.thoughtworks.xstream.converters.marshallingcontext; import com.thoughtworks.xstream.converters.unmarshallingcontext; import com.thoughtworks.xstream.io.hierarchicalstreamreader; import com.thoughtworks.xstream.io.hierarchicalstreamwriter;  public class ratingconverter implements converter {      @override     public boolean canconvert(class clazz) {         return clazz.equals(rating.class);     }      @override     public void marshal(object value, hierarchicalstreamwriter writer,             marshallingcontext context)      {         rating rating = (rating) value;          // write id         writer.startnode("id");         writer.setvalue(rating.getid());         writer.endnode();          // write score         writer.startnode("score");         writer.setvalue(integer.tostring(rating.getscore()));         writer.endnode();          // write confidence         if(rating.getconfidence() != 0)         {             writer.startnode("confidence");             writer.setvalue(integer.tostring(rating.getconfidence()));             writer.endnode();         }     }      @override     public object unmarshal(hierarchicalstreamreader arg0,             unmarshallingcontext arg1)     {         return null;     } } 

all that's left register converter, , provide accessor methods (i.e. getid, getscore, getconfidence) in rating class.

note: other option omit field appropriately.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -