Search code examples
javajsoncxfjax-rsjettison

Custom JSON Date handling in CXF


I'm using apache CXF to create a JAX-RS service that consumes multipart/form-data, one of the parts is application/json which I'm handling in a Java bean. The problem that I have is that the date format being passed in is not recognised by the standard jettison deserialiser and I just get null.

The service is:

@POST
@Path("/blah/")
@Consumes("multipart/form-data")
public String doBlah(MultipartBody body)
{
        JSON json = atts.get(0).getObject(JSON.class);
}

The JSON object is:

class JSON {
    Date date;
}

The date passed in is something like: November 25, 2012 13:35:24 which i know how to convert using SimpleDateFormat, so I can change the JSON to have a string and i get the value and can then manually do the conversion ... BUT how do you register a class in CXF to do the conversion in jettison?

Is there a config in beans.xml or something where i can add a custom handler and/or override the default Date handling?


Solution

  • You can register a custom date handler in Spring as follows:

    <jaxrs:server …>
        <jaxrs:providers>
            <bean class='….DateHandler' />
        </jaxrs:providers>
    </jaxrs:server>
    

    The date handler class itself can be pretty simple:

    public class DateHandler implements ParameterHandler<Date> {
        @Override
        public Date fromString(String s) {
            Date ret = // do your magic
            return ret;
        }
    }