jersey - json(jsonp 跨域)格式交互

来源:互联网 发布:淘宝店铺首页宝贝展示 编辑:程序博客网 时间:2024/06/06 12:27

JacksonFeature.class

在使用Tomcat作为HttpServer时,需要特别注意,实现java对象到json的解析时必须注册到JacksonFeature类,自己写的MyProvider不行。

//自己写MyProvider 不能用,不知道为什么@Providerpublic class MyProvider implements ContextResolver<ObjectMapper> {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依赖为:

<dependency><groupId>org.glassfish.jersey.media</groupId><artifactId>jersey-media-json-jackson</artifactId><version>2.5</version></dependency>

主文件写法见下:

package com.likeyichu.webservice;import org.glassfish.jersey.jackson.JacksonFeature;import org.glassfish.jersey.server.ResourceConfig;public class App extends ResourceConfig {<span style="white-space:pre"></span>public  App() {<span style="white-space:pre"></span>//向jersey框架注册资源类,凡完全限定名是以指定字符串开头的类,都将包含<span style="white-space:pre"></span>packages("com.likeyichu.webservice");<span style="white-space:pre"></span>register(JacksonFeature.class);<span style="white-space:pre"></span>}}


getter()

要序列化为json的对象应该实现setter与getter方法。可以定义完成员变量后用Eclipse自动生成,见下图。


效果


注意

若一个类想要被序列化,必须有public 权限。
加@Produces标注的函数,函数名不要以“get”开头,不然jackson会无穷递归下去。

jersey-jsonp

@org.glassfish.jersey.server.JSONP
jersey框架帮我们返回jsonp格式的内容。一个实例:
@Path("jsonp")@GET@JSONP(queryParam="callback")//返回的函数名与http请求中的callback参数的值一致@Produces("application/x-javascript")  //这里最好写成application/x-javascriptpublic Student wsStudent2( ) {return new Student();}
效果:

jersey-post

@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;}



2 0
原创粉丝点击