java学习

java学习

 

jersey面向资源开发5

前端传递json数据,配置第一种方法
<!-- media type -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>${jersey.version}</version>
</dependency>
@ApplicationPath("/webapi/*")
public class AirResourceConfig extends ResourceConfig {
    public AirResourceConfig() {
     //   packages("com.example.resource");   
        register(BookResource.class);
    }
}
前端传递json数据,配置第二种方法
  <!-- media type -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
@ApplicationPath("/api/*")
public class JsonResourceConfig extends ResourceConfig {
    public JsonResourceConfig() {
        register(BookResource.class);
        register(JacksonFeature.class);
        register(JsonContextProvider.class);
    }
}
@Provider
public class JsonContextProvider implements ContextResolver<ObjectMapper> {
    final ObjectMapper d;
    final ObjectMapper c;
    public JsonContextProvider() {
        d = createDefaultMapper();
        c = createCombinedMapper();
    }
    private static ObjectMapper createCombinedMapper() {
        Pair ps = createIntrospector();
        ObjectMapper result = new ObjectMapper();
        //result.configure(Feature.WRAP_ROOT_VALUE, true);
        //result.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
        result.setDeserializationConfig(result.getDeserializationConfig().withAnnotationIntrospector(ps));
        result.setSerializationConfig(result.getSerializationConfig().withAnnotationIntrospector(ps));
        return result;
    }
    private static ObjectMapper createDefaultMapper() {
        ObjectMapper result = new ObjectMapper();
        result.configure(Feature.INDENT_OUTPUT, true);
        return result;
    }
    private static Pair createIntrospector() {
        AnnotationIntrospector p = new JacksonAnnotationIntrospector();
        AnnotationIntrospector s = new JaxbAnnotationIntrospector();
        return new Pair(p, s);
    }
    @Override
    public ObjectMapper getContext(Class<?> type) {
        if (type == JsonHybridBook.class) {
            return c;
        } else {
            return d;
        }
    }
}

posted on 2017-07-31 17:44 杨军威 阅读(132) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜