我很好奇为什么你使用Jackson 1.x而不是2.x?两者的说明相似,但 Jackson 配置必须改变 . 以下是1.x的说明 .
jboss-deployment-structure.xml(和你的一样):
使用@Application注册您的应用程序:
@ApplicationPath("/api/v1")
public class V1Application extends Application {
@Override
public Set> getClasses() {
Set> classes = new HashSet>();
classes.add(JacksonConfigurationProvider.class);
classes.add(TestResource.class);
return classes;
}
}
使用jackson配置提供程序,例如:
@Provider
@Consumes({MediaType.APPLICATION_JSON, "text/json"})
@Produces({MediaType.APPLICATION_JSON, "text/json"})
public class JacksonConfigurationProvider extends ResteasyJacksonProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(JacksonConfigurationProvider.class);
public JacksonConfigurationProvider() {
super();
LOGGER.info("loading jackson configurator");
JacksonObjectMapper mapper = JacksonObjectMapper.get();
setMapper(mapper);
}
}
然后,在您的JacksonObjectMapper中,您可以告诉它阅读注释:
public class JacksonObjectMapper extends ObjectMapper {
public static JacksonObjectMapper get() {
JacksonObjectMapper mapper = new JacksonObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
JacksonAnnotationIntrospector jacksonAnnotationIntrospector = new JacksonAnnotationIntrospector();
mapper.setDeserializationConfig(mapper.getDeserializationConfig().withAnnotationIntrospector
(jacksonAnnotationIntrospector));
mapper.setSerializationConfig(mapper.getSerializationConfig().withAnnotationIntrospector
(jacksonAnnotationIntrospector));
return mapper;
}
}
我的 Jackson 对象看起来像这样:
@JsonRootName("foobar")
public class TestType {
@JsonProperty("goodbye")
String hello;
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
作为一个方便我也在我的web.xml中有这个,它允许你通过将.json放在URL而不是设置 Headers 来请求json:
resteasy.media.type.mappings
json : application/json, xml : application/xml
{
"foobar": {
"goodbye": "Here is some random string"
}
}