JAX-RS joda datetime from json

547 views Asked by At

I am building an API using java and the following libraries

  • javax.ws.rs-api-2.0.1
  • genson-1.4
  • joda-time-2.9.6

I am now trying to create a post request with a list of object as a parameter

@Path("service")
public class ServiceResource {

    @Path("/stations/flow/forecasts")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public List<Station> getStations(List<Station> stations) {
            //Code
    }
}

This class Station contains a list of another class which has a DateTime variable.

The data are sent from a web app using javascript. It is working fine when I am not sending the nested list with the datetime object. When I try to send it I receive the error :

java.lang.InstantiationException

The json sent looks like this

[
   {
      "code":"1048",
      "measures":[
         {
            "code":"10481002",
            "observations":[
               {
                  "date":{
                     "chronology":{
                     },
                     "millis":1487322000000
                  },
                  "value":1.702
               }
            ]
         }
      ]
   }
]

And the java class linked to this date and value

public class Value {
    private DateTime date;
    private Float value;
}

How is the code not working when sending the DateTime ?

Note: Everything else is working fine in the API : posting an user object, get data containing datetime, sending back datetime

EDIT

I found out that there is an extension for joda-time. I added the following code

@Provider
public class GensonProvider implements ContextResolver<Genson> {
    private final Genson genson = new GensonBuilder().useConstructorWithArguments(true).useDateAsTimestamp(false).withBundle(new JodaTimeBundle()).create();

    @Override
    public Genson getContext(Class<?> type) {
        return genson;
    }
}

But it still gives me the same result

1

There are 1 answers

4
eugen On

Your date format is not standard. Change this

"date":{
  "chronology":{
  },
  "millis":1487322000000
}

to "date": 1487322000000 or to a string formatted date (in which case you will want to configure Genson to parse your format).