博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jersey - json(jsonp 跨域)格式交互
阅读量:7100 次
发布时间:2019-06-28

本文共 1614 字,大约阅读时间需要 5 分钟。

JacksonFeature.class

在使用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);	}}

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-javascript	public 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;	}
你可能感兴趣的文章
Linux DNS 服务器介绍
查看>>
SpringMVC 使用hibernate返回list
查看>>
微寻,如何实现移动医疗?
查看>>
一个具有菜单选项的简单shell脚本
查看>>
Ecshop架构分析流程图
查看>>
Git详解之六 Git工具
查看>>
zookeeper 伪集群
查看>>
RabbitMQ 消息确认
查看>>
Ubuntu打印服务器配置
查看>>
用模型取代字典的好处
查看>>
我的友情链接
查看>>
Windows Server 2012组策略改进
查看>>
shell 打印顺倒三角
查看>>
Fedora 17 Gnome 3 备用模式
查看>>
我的友情链接
查看>>
Mac 键盘快捷键
查看>>
FastDFS海量数据分布式存储方案
查看>>
Nginx实战之--后端节点健康检查
查看>>
redhat 5.3 安装mysql详细步骤
查看>>
Openstack Mitaka for Centos7.2 部署指南(二)
查看>>