Search code examples
javascalaxstream

How to unmarshall XML with default value as empty string using XStream?


I am trying to figure out how to unmarshall XML when a tag is missing, I can set the default value as empty string instead of NULL. Currently XStream is using null, which is not what I want.

This class has like over 40 properties, which are all String. There is a constructor with default value for each. I mean, like this:

case class MyData(id: String = "", b: String = "", ....) 

(yes, I am trying to use it with Scala)

Technically I could write a custom converter that sets them as empty string, but that feels a little silly.

I tried using this

new XStream(new PureJavaReflectionProvider()) 

as suggested from here: https://stackoverflow.com/a/29747705/598562

It doesn't seem to work though.

any other idea?


Solution

  • XStreams uses a default, empty constructor and then follows it up by calling setters afterwards. So, to get this to work without a custom converter then you will need to create an explicit empty constructor which fills everything in with the defaults you expect. Here is a sample, working application:

    import com.thoughtworks.xstream.XStream
    import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider
    
    object Hello extends App {
      val xstream = new XStream(new PureJavaReflectionProvider())
      xstream.alias("MyData", classOf[MyData])
      val output = xstream.fromXML("<MyData><id>This should fill in</id></MyData>")
      println(output)
    }
    
    case class MyData(id: String = "", var b: String = "") 
    {
       def this() = this("", "")
    }