Jersey JSON serialization

前端 未结 2 1979
天涯浪人
天涯浪人 2021-01-19 13:44

I set up an eclipse WebApp project and placed Jersey and Jackson JARs in the WEB-INF/lib directory. I want to use JSON serialization but didn\'t manage to fix this error:

2条回答
  •  野的像风
    2021-01-19 14:18

    All you need is to register JacksonJsonProvider. There are many ways to achieve that:

    1. Register the JacksonJsonProvider explicitly in web.xml:
    
        jersey.config.server.provider.classnames
        com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider
    
    

    or

    1. Register your class extending javax.ws.rs.core.Application in the web.xml
    
        javax.ws.rs.Application
        com.rest.MyApplication
    
    

    and then do all the configuration in the application class:

    package com.rest;
    
    import org.glassfish.jersey.server.ResourceConfig;
    import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
    
    public class MyApplication extends ResourceConfig {
    
        public MyApplication() {
            packages("com.rest");
            register(JacksonJsonProvider.class);
        }
    

    ResourceConfig is a subclass of javax.ws.rs.Application and gives you some helper methods that makes the registration easy.

    or

    1. Use automatic registration. Just add dependency to jersey-media-json-jackson
    
        org.glassfish.jersey.media
        jersey-media-json-jackson
        2.13
    
    

    But be careful. It will register more than you need:

    • JacksonJaxbJsonProvider,
    • JsonParseExceptionMapper,
    • JsonMappingExceptionMapper

    Take a look at the source code to see what it does.

提交回复
热议问题