gpt4 book ai didi

java - 重用 Jackson ObjectMapper 和 JsonFactory 实例

转载 作者:行者123 更新时间:2023-11-30 06:56:56 36 4
gpt4 key购买 nike

( jackson 2.6.1, Jersey 2.21.0)

我的网络应用程序使用 JAX-RS 接口(interface)和 Jackson json 帮助程序类。我不直接导入 Jersey 类,计划让它与我的应用程序无关。

我想按照 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() 方法中设置私有(private)静态对象映射器字段吗?

这是我提供 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

设置休息服务并配置对象映射器实例,例如日期时间字段格式。

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();
}
}

最佳答案

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。如果未找到,则它会为 ObjectMapper 寻找 ContextResolver。如果没有找到,它将只使用它自己的 ObjectWriterObjectReader

因此您不需要使用 ObjectMapper 创建 JacksonJaxbJsonProvider。只需使用 default constructor ,提供商将寻找您的解析器。

关于java - 重用 Jackson ObjectMapper 和 JsonFactory 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33924570/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com