本文共 1614 字,大约阅读时间需要 5 分钟。
在使用Tomcat作为HttpServer时,需要特别注意,实现java对象到json的解析时必须注册到JacksonFeature类,自己写的MyProvider不行。
//自己写MyProvider 不能用,不知道为什么@Providerpublic class MyProvider implements ContextResolver{ public ObjectMapper getContext(final Class type) { final ObjectMapper mapper=new ObjectMapper(); return mapper ; }}
class JacksonFeature所在的jar为jersey-media-json-jackson-2.5.jar,这个jar只有它一个类。
它的maven依赖为:
主文件写法见下:org.glassfish.jersey.media jersey-media-json-jackson 2.5
package com.likeyichu.webservice;import org.glassfish.jersey.jackson.JacksonFeature;import org.glassfish.jersey.server.ResourceConfig;public class App extends ResourceConfig { public App() { //向jersey框架注册资源类,凡完全限定名是以指定字符串开头的类,都将包含 packages("com.likeyichu.webservice"); register(JacksonFeature.class); }}
要序列化为json的对象应该实现setter与getter方法。可以定义完成员变量后用Eclipse自动生成,见下图。
@Path("jsonp") @GET @JSONP(queryParam="callback")//返回的函数名与http请求中的callback参数的值一致 @Produces("application/x-javascript") //这里最好写成application/x-javascript public Student wsStudent2( ) { return new Student(); }效果:
@Path("post") @POST @Consumes(MediaType.APPLICATION_JSON) //因为这行,wsStudent3()的形参remoteStudent会被jersey注入 @Produces(MediaType.APPLICATION_JSON) public Student wsStudent3(Student remoteStudent) { Student student= new Student(); student.setName(student.getName()+remoteStudent.getName()); return student; }