3

I'm using Jersey for my RESTful services and Genson to perform my JSON/POJO conversion. There's no setup for Genson, I just drop it into the classpath and it just works, except that it throws an error on date parsing because the format is unexpected.

Now, if I were to do this as a servlet, using Gson, I set the date format on a Gson instance that I maintain. That forces the parse of the POJO to use the correct format. I see that Genson has a similar interface, but I don't know how to get the instance from the Jersey servlet service or maybe the Spring context so that I cat set the format.

So, the short question is: how do I set a date format for Genson when started through Jersey?

informatik01
  • 16,038
  • 10
  • 74
  • 104
user1442498
  • 305
  • 2
  • 10

1 Answers1

3

To configure Genson instances you can use Genson.Builder class (it is similar to Gson on this point). Then you have to inject it with Jersey.

@Component
@Provider
public class GensonProvider implements ContextResolver<Genson> {
   private final Genson genson = new Genson.Builder().setDateFormat(yourDateFormat).create();

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

You might also want to have a look at how Genson is integrated into Jersey here.

informatik01
  • 16,038
  • 10
  • 74
  • 104
eugen
  • 5,856
  • 2
  • 29
  • 26
  • Could u know the reason why Jersey does not use my Genson ContextResolver. I registered it manually with ResourceConfig class but the Resolver is never called. :( – Orri Oct 15 '13 at 08:51
  • There can be a lot of reasons. You should open a new question to show some code and post the link to it here. – eugen Oct 15 '13 at 09:44
  • Date conversion in required format is working fine and am setting it to UTC time zone. But in my Request object it is not in UTC time zone. It is in my server time zone. – Arun Oct 01 '15 at 09:54
  • I faced the same problem as faced by Orri. My `ContextResolver` was not being identified. I had to put it the same package as specified in my `web.xml` for `com.sun.jersey.config.property.packages` (where I've also put my services). – RAS Feb 03 '17 at 12:23