How to conditionally serialize a field (attribute) using XStream

I use XStream to serialize and de-serialize an object. For example, a class named Rating is defined as follows:

 Public Class Rating { String id; int score; int confidence; // constructors here... } 

However, in this class, the confidence variable is optional.

So, when the confidence value is known (and not 0), the XML representation of the Rating object should look like this:

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

However, when trust is unknown (the default value is 0), the trust attribute must be omitted from the XML view:

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

Can someone tell me how to conditionally serialize a field using XStream?

+4
source share
1 answer

One option is to write converter .

Here is the one I quickly wrote for 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 you have to do is register the converter and provide access methods (i.e. getId, getScore, getConfidence) in your Rating class.

Note. Another option would be to omit the field accordingly.

+6
source

Source: https://habr.com/ru/post/1340232/


All Articles