我正在
找不到媒体类型= application / json的MessageBodyWriter,type = class java.util.HashMap $ Values,genericType = java.util.Collection
来自Glassfish 4.1的Web服务。我看到的一切都说在类路径中有jackson或其他库,以便可以转换类型。有了Glassfish,我有:
~/apps/glassfish-4.1/glassfish/domains/domain1/logs$ find ../../../../ | grep jackson
../../../../glassfish/modules/jackson-core.jar
../../../../glassfish/modules/jackson-annotations.jar
../../../../glassfish/modules/jackson-databind.jar
../../../../glassfish/modules/jackson-jaxrs-json-provider.jar
../../../../glassfish/modules/jackson-jaxrs-base.jar
../../../../glassfish/modules/jersey-media-json-jackson.jar
实体类:
public class Actor extends AbstractBaseEntity{
public Actor(String id, String name) {
super(id, name);
}
}
public class AbstractBaseEntity {
String identifier;
String name;
public AbstractBaseEntity(String id, String name){
this.identifier = id;
this.name = name;
}
public String getIdentifier() {
return identifier;
}
public String getName() {
return name;
}
}
服务类:
@Path("actors")
public class MockActorService {
private static final int DEFAULT_COUNT = 5;
HashMap<String, Actor> items;
public MockActorService() throws WFlowServiceException {
this(MockActorService.DEFAULT_COUNT);
}
public MockActorService(int actors) throws WFlowServiceException {
items = new HashMap<>();
for (int i = 0; i < actors; i++) {
Actor a = new Actor("ID:" + i, "Actor Name " + i);
items.put(a.getIdentifier(), a);
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAll() throws WFlowServiceException {
GenericEntity< Collection< Actor > > entity;
Collection<Actor> vals = items.values();
entity = new GenericEntity<Collection<Actor>>(vals){};
return Response.ok(entity).build();
}
}
为什么我仍然会收到此错误?
答案 0 :(得分:0)
是的,Glassfish有杰克逊,但它也有MOXy,这是默认的提供者。某些类型的MOXy很奇怪。如果要禁用MOXy以便可以使用Jackson,则需要将以下属性设置为true
我暂时没有使用Glassfish,所以我不确定你是否还需要注册杰克逊,但我很确定你不会。它应该自动注册。 MOXy基本上阻止它被注册。
答案 1 :(得分:0)
好的,经过一番挖掘后,我想出了以下内容来解决它。 @peeskillet部分正确,此修复程序是Glassfish特定的。
Here is the blog with more context
这是修复它的原因。我需要实现以下两个类:
public class JacksonFeature implements Feature {
Logger L = LoggerFactory.getLogger(JacksonFeature.class);
@Override
public boolean configure(final FeatureContext context) {
String postfix = "";
postfix = '.' + context.getConfiguration().getRuntimeType().name().toLowerCase();
context.property(CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix, true);
L.info("Set property to true disable MOXY: " + CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix);
context.register(JsonParseExceptionMapper.class);
context.register(JsonMappingExceptionMapper.class);
context.register(JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
return true;
}
}
@javax.ws.rs.ApplicationPath("api")
public classMyResourceConfig extends ResourceConfig {
publicMyServicesResourceConfig() {
register( new GZipEncoder() );
register( JacksonFeature.class );
addMyResources();
}
private void addMyResources() {
register( Service1.class );
register( Service2.class );
}
}