PrettyPrint JavaScript

martedì 3 marzo 2015

Deserialize XMLGregorianCalendar from JSON using flexjson-2.1

In order to deserialize an XMLGregorianCalendar flexjson raise a JSonException with the following message: "There was an exception trying to instantiate an instance of javax.xml.datatype.XMLGregorianCalendar" This occours because the class XMLGregorianCalendar has not a default constructor with no parameter as flexjson is supposed to have. To avoid this you need to implement the flexjson.ObjectFactory interface to instantiate and build a well-defined XMLGregorianCalendar object. Suppose we have a simple class as follows:
public class Foo{
 
   private XMLGregorianCalendar startDate;
   
   private XMLGregorianCalendar endDate;

   public XMLGregorianCalendar getStartDate(){return startDate;}

   public void setStartDate(XMLGregorianCalendar start){this.startDate = start;}
   
   public XMLGregorianCalendar getEndDate(){return endDate;}
   
   public void setEndDate(XMLGregorianCalendar end){this.endDate = end;}


}
Example of ObjectFactory implementation:
public class XMLGregorianCalendarFactory implements ObjectFactory {

 @Override
 public Object instantiate(ObjectBinder context, Object value, Type targetType,
   Class targetClass) {
    
  try {
   XMLGregorianCalendar result = DatatypeFactory.newInstance().newXMLGregorianCalendar();
   JSONDeserializer jd = new JSONDeserializer();
   String input =  new JSONSerializer().deepSerialize(value);
   jd.deserializeInto(input, result);
   return result;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

}
To force flexjson uses our implementation, we need to pass it with the use method, as shown below:
JSONDeserializer jd = new JSONDeserializer();
jd.use(XMLGregorianCalendar.class, new XMLGregorianCalendarFactory());
Foo target = new Foo();
jd.deserializeInto(json, target);
After jd.deserializeInto(json, target) execute, the target object Foo will be correctly instatiate. (If we provide a valid json string!)