Create A Custom Json String Deserializer Inwards Java

On normal cases nosotros actually convey a lot of ways inwards doing so, nosotros tin exercise jaxb, jackson in addition to more.

But inwards closed to cases nosotros actually bespeak to improvised, for illustration inwards the projection I'm working right immediately I convey a engagement string from a .net application inwards this format: "2014-04-08T07:08:48.1344874Z". As you lot tin encounter it has vii characters inwards the millisecond section, patch coffee commonly exercise 3. Of course of pedagogy you'll nation but exercise a simpleDateFormat that volition parse the vii characters, I've idea of that in addition to here's the result

SimpleDateFormat df1 = novel SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX"); Date d1 = df1.parse("2014-04-07T15:20:40.7439627Z"); System.out.println("D1: " + d1);  // produces "Mon April 07 19:24:39 CEST 2014"  //as I said it works on iii grapheme millies SimpleDateFormat df2 = novel SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); Date d2 = df2.parse("2014-04-07T15:20:40.743Z"); System.out.println("D2: " + d2);  // produces "Mon April 07 17:20:40 CEST 2014" 

Note that I'm using UTC+2.

I works life a solution that is worth mentioning, although it didn't actually operate 100% for me. Normally when you lot generate classes from xsd using xjc, it volition exercise an XmlGregorianCalendar object. So the offset occupation is how volition I convert it to a Date object?

1.) Create a xs:dateTime binding, xs:dateTime is what you'll encounter inwards your xsd.
<?xml version="1.0" encoding="UTF-8"?> <bindings xmlns="http://java.sun.com/xml/ns/jaxb" version="2.0"  xmlns:xs="http://www.w3.org/2001/XMLSchema">   <globalBindings>   <javaType name="java.util.Date" xmlType="xs:dateTime"    parseMethod="org.czetsuya.xsd.converter.XsdDateTimeConverter.unmarshal"    printMethod="org.czetsuya.xsd.converter.XsdDateTimeConverter.marshalDateTime" />   <javaType name="java.util.Date" xmlType="xs:date"    parseMethod="org.czetsuya.xsd.converter.XsdDateTimeConverter.unmarshal"    printMethod="org.czetsuya.xsd.converter.XsdDateTimeConverter.marshalDate" />  </globalBindings>  </bindings> 

2.) Generate the coffee shape from xsd, I commonly exercise it via eclipse using the jaxb converter from jaxb schema to coffee class.

What it does is exercise a JavaType adapter in addition to supercede XmlGregorianCalendar amongst a engagement object. The xs:dateTime fields volition endure annotated similar this:
 
@XmlJavaTypeAdapter(Adapter1 .class) @XmlSchemaType(name = "dateTime") protected Date myDate; 

And it volition work, in addition to and then I idea but it did non :-) Same occupation I pull earlier. Btw, I'm using jackson ObjectMapper to parse a json string into an object similar this:
 
ObjectMapper mapper = ObjectMapperFactory.createObjectMapper(); messageWrapper = mapper.readValue(message, MyClass.class); 

That code successfully parsed my json string but the engagement values are nevertheless totally incorrect no affair the information type.

And in addition to then the finally exercise of the solution. Customizing a Json de-serializer for object of type Date. See our XmlGregorianCalendar to Date comes into place.

So our converter:
package org.czetsuya.xsd.converter;  import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar;  import javax.xml.bind.DatatypeConverter;  import org.apache.log4j.Logger; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.DeserializationContext; import org.codehaus.jackson.map.JsonDeserializer;  /**  * @author Edward P. Legaspi  **/ populace shape XsdDateTimeConverter extends JsonDeserializer {   protected static Logger log = Logger.getLogger(XsdDateTimeConverter.class);   populace static Date unmarshal(String dateTime) {   furnish DatatypeConverter.parseDate(dateTime).getTime();  }   populace static String marshalDate(Date date) {   finally GregorianCalendar calendar = novel GregorianCalendar();   calendar.setTime(date);   furnish DatatypeConverter.printDate(calendar);  }   populace static String marshalDateTime(Date dateTime) {   finally GregorianCalendar calendar = novel GregorianCalendar();   calendar.setTime(dateTime);   furnish DatatypeConverter.printDateTime(calendar);  }   @Override  populace Date deserialize(JsonParser jp, DeserializationContext ctxt)    throws IOException, JsonProcessingException {   // format: 2014-04-08T07:08:48.1344874Z   String engagement = jp.getText();   if (date == cypher || date.length() != 28) {    log.debug("Null or invalid date=" + date);    furnish null;   }    // take away extra four milliseconds   engagement = date.substring(0, date.length() - 5)     + date.charAt(date.length() - 1);    SimpleDateFormat sf = novel SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");   endeavor {    furnish sf.parse(date);   } select grip of (ParseException e) {    log.error("Error parsing date=" + date);    furnish null;   }  } } 

Well you lot tin disregard the offset iii methods every bit it actually non use. The most of import exercise is inwards the deserialize method. It removes the finally four millisecond characters in addition to then coffee tin sympathize in addition to parse it to a Date object. But how volition the mapper know almost this converter, of course of pedagogy you lot convey to tell it :-)
 
 
ObjectMapper mapper = novel ObjectMapper(); SimpleModule module = novel SimpleModule("czetsuya", Version.unknownVersion()); module.addDeserializer(Date.class, novel XsdDateTimeConverter()); mapper.registerModule(module); 

And that's it when you lot telephone telephone the reader from the mapper it should immediately parse the right value of engagement string.

References:
http://stackoverflow.com/questions/6553051/setting-up-json-custom-deserializer
http://stackoverflow.com/questions/5106987/jax-ws-and-joda-time
http://www.baeldung.com/jackson-deserialization
http://stackoverflow.com/questions/21706415/jackson-objectmapper-using-custom-serializers-and-deserializers
http://blog.palominolabs.com/2012/06/05/writing-a-custom-jackson-serializer-and-deserializer/
Next
Previous
Click here for Comments

0 komentar:

Please comment if there are any that need to be asked.