重用Jackson ObjectMapper和JsonFactory实例

时间:2015-11-25 19:07:32

标签: java jackson jax-rs jersey-2.0

(Jackson 2.6.1,Jersey 2.21.0)

我的webapp使用JAX-RS接口和Jackson json助手类。我不直接导入泽西岛课程,计划保持与我的应用程序无关。

我希望像Jackson文档推荐的那样重用ObjectMapper和JsonFactory实例,但是无法在MyBeanService类中引用它们。

// resolver returns null
ContextResolver<ObjectMapper> resolver = providers.getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE);
ContextResolver<JacksonJaxbJsonProvider> resolverB = providers.getContextResolver(JacksonJaxbJsonProvider.class, MediaType.WILDCARD_TYPE);
// returns org.glassfish.jersey.server.ResourceConfig$WrappingResourceConfig wrapper
// also I wish not to import directly any jersey classes
ContextResolver<Application> resolverC = providers.getContextResolver(Application.class, MediaType.WILDCARD_TYPE);

// resolver was null so getters don't work
ObjectMapper mapper = resolver.getContext(ObjectMapper.class);
JsonGenerator jsonG = mapper.getFactory().createGenerator(os, JsonEncoding.UTF8);

我应该只提供public static ObjectMapper MyApplication.getObjectMapper()功能吗? MyApplication会在getSingletons()方法中设置私有静态objectmapper字段吗?

这是我提供restjson servlet路径的配置和类。

mywebapp / WEB-INF / web.xml中

web.xml文件中给出的应用程序实例。

...
<servlet><servlet-name>myapp.rest.MyApplication</servlet-name></servlet>
<servlet-mapping>
   <servlet-name>myapp.rest.MyApplication</servlet-name>
   <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

MyApplication.java

设置休息服务并配置objectmapper实例,例如datetime字段格式。

package myapp.rest;

import java.util.*;
import java.text.*;
import javax.ws.rs.core.Application;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.jaxrs.cfg.Annotations;

public class MyApplication extends Application {

    @Override public Set<Class<?>> getClasses() {
        Set<Class<?>> list = new HashSet<Class<?>>();
        list.add(MyBeanService.class);
        return list;
    }

    @Override public Set<Object> getSingletons() {
        Set<Object> list = new HashSet<Object>();

        ObjectMapper mapper = new ObjectMapper();       
        mapper.disable(SerializationFeature.INDENT_OUTPUT);
        //mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // enable=1433435279692 (utcMillis)
        //mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // disable=2015-06-04T16:25:27.056+0000 (ISO8601_utc) 
        DateFormat dtf = SimpleDateFormat.getDateTimeInstance();
        ((SimpleDateFormat)dtf).applyPattern("yyyy-MM-dd'T'HH:mm:ssZ"); // 2015-06-04T19:25:27+0300 (custom+tzOffset)
        mapper.setDateFormat(dtf);
        JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(
                mapper, 
                new Annotations[] { Annotations.JACKSON, Annotations.JAXB } );
        list.add(provider);     
        return list;
    }

}

MyBeanService.java

这是一个处理rest url路径的服务类。

import java.io.*;
import java.util.*;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.StreamingOutput;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.*;

@Path("") @Singleton
public class MyBeanService {
    //@Context private Providers providers;
    //@Context private Application application;

    @GET @Path("/{serverName}/beans/{id}")
    @Produces({"application/json;charset=UTF-8"})
    public Response getBean (
            @Context HttpServletRequest req,
            @PathParam("serverName") String serverName,
            @PathParam("id") long id) {

        final MyServer server= JPADB.getServer(serverName);
        final MyBean bean    = JPADB.getBean(server, id);

        StreamingOutput stream = new StreamingOutput() {
           @Override public void write(OutputStream os) throws IOException, WebApplicationException {
              //*** I want to reuse JsonFactory and ObjectMapper, but
              // currently create new factory each time
              JsonFactory jsonF = new JsonFactory();
              JsonGenerator jsonG = jsonF.createGenerator(os, JsonEncoding.UTF8);
              try {
                 jsonG.writeStartObject();
                 jsonG.writeNumberField("id", bean.getId());
                 jsonG.writeStringField("title", bean.getTitle());
                 jsonG.writeStringField("serverId", server.getId());
                 jsonG.writeStringField("serverName", server.getName());
                 ..various json fields, some optional, some at runtime autogen..
                 jsonG.writeEndObject();
                 jsonG.flush();
              } finally {
                 jsonG.close();
              }
           }
        };

        CacheControl cc = new CacheControl();
        cc.setNoCache(true);
        return Response.ok().type("application/json;charset=UTF-8")
                .cacheControl(cc).entity(stream).build();
    }
}

1 个答案:

答案 0 :(得分:4)

ContextResolver为空,因为您实际上 没有ContextResolver。这是你需要自己写的东西。

@Provider
@Produces("application/json")
@Consumes("application/json")
public class MapperContextResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper mapper;

    public MapperContextResolver() {
        mapper = new ObjectMapper();
        // do any configurations to mapper
    }

    @Override
    public ObjectMapper getContext(Class<?> cls) {
        return mapper;
    }
}

然后只需将其注册到应用程序即可。 Jackson(Jaxb)JsonProvider的工作原理是首先查找传递给构造函数的ObjectMapper。如果找不到,则会为ContextResolver查找ObjectMapper。如果找不到,它将只使用自己的ObjectWriterObjectReader

因此,您无需使用JacksonJaxbJsonProvider创建ObjectMapper。只需使用default constructor,提供商就会查找您的解析器。