Sunday, 3 January 2016

XML : Unmarshaling Java data types using JAXB & Groovy

I'm new to JAXB and attempting to map datatypes in a JAXB class to their Java equivalent but it always insists on returning a string.

Given the following XML:

  <Response>      <Label>shiftStartTime</Label>      <Value>06:30</Value>      <Type>Time</Type>  </Response>    

we can see that the that the type is declared in the element. What I want is to have the value returned as a Joda Time LocalTime.

My code at the moment is as follows:

  import org.joda.time.format.DateTimeFormat  import org.joda.time.format.DateTimeFormatter  import javax.xml.bind.annotation.XmlRootElement  import javax.xml.bind.annotation.XmlElement  import javax.xml.bind.annotation.XmlAccessorType  import javax.xml.bind.annotation.XmlAccessType    @XmlRootElement(name="ResponseGroup")  @XmlAccessorType(XmlAccessType.FIELD)  class Response {        @XmlElement(name="Label")      private String label        @XmlElement(name="Value")      private String value        @XmlElement(name="Type")      private String type        DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd/MM/yyyy");      DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("HH:mm");        def stringTypes = ["GPS", "Static Text", "Multi-Line Text", "Value List", "Image Capture", "Signature", "Text Box"]      def integerTypes = ["Integer"]      def doubleTypes = ["Summary", "Calculation", "Decimal"]      def timeTypes = ["Time"]      def dateTypes = ["Date"]      def booleanTypes = ["Checkbox"]        public String getLabel() {          return label      }        public String getType() {          return type      }        def getValue(){            if(stringTypes.contains(this.type)){              return this.value.toString()          }          else if (integerTypes.contains(this.type)){              return this.value.toInteger()          }          else if (doubleTypes.contains(this.type)){              return Double.parseDouble(this.value)          }          else if (timeTypes.contains(this.type)){              return timeFormatter.parseLocalTime(this.value)          }          else if (dateTypes.contains(this.type)){              return dateFormatter.parseLocalDate(this.value)          }          else if (booleanTypes.contains(this.type)){              return this.value.toBoolean()          }          else {              // Hoping for the best and returning a string              return this.value.toString()          }      }  }    

I can see in the dubugger that the code in the getValue() method is being run, however the result is always returned as a 'String'. I'm clearly missing something as there must be a way in JAXB to map the Java type depending an the element.

No comments:

Post a Comment