XStream null value を出力するケース、再び書き直す。

先日書いた、カスタムのコンバータで、XStream でXML出力する時の NULL の値のタグを書くケース、
HierarchicalStreamWriter を BiConsumer で渡して書かせるなんてやはりセンスないので、、、


oboe2uran.hatenablog.com

先日の方法ではなく、NULL で空タグを書かせるべきかどうかの Fucntionラムダ関数にした方が良い。

import java.util.function.Function;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
/**
 * CustomEmptyConverter
 */
public class CustomEmptyConverter extends ReflectionConverter{
   private Function<Object, String> emptywriter;
   /**
    * コンストラクタ.
    */
   public CustomEmptyConverter(Mapper mapper, Function<Object, String> emptywriter){
      super(mapper, new SunUnsafeReflectionProvider);
      this.emptywriter = emptywriter;
   }
   @Override
   protected void doMarshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context){
      super.doMarshal(object, writer, context);
      String tagname = emptywriter.apply(object);
      if (tagname != null){
         writer.startNode(tagname);
         writer.setValue("");
         writer.endNode();
      }
   }
}


サンプル

XStream stream = new XStream(new DomDriver("UTF-8"));

CustomEmptyConverter emptyConverter = new CustomEmptyConverter(stream.getMapper(), e->{
   if (e instanceof Root){
      if (((Root)e).date==null) return "date";
   }
   return null;
});
stream.registerConverter(emptyConverter, XStream.PRIORITY_VERY_LOW);