Spring MVC 学习笔记 九 json格式的输入和输出

本文介绍SpringMVC中处理JSON数据的方法,包括使用@RequestBody和HttpEntity进行JSON输入绑定,以及通过@ResponseBody和ContentNegotiatingViewResolver实现JSON输出。

Spring mvc处理json需要使用jackson的类库,因此为支持json格式的输入输出需要先修改pom.xml增加jackson包的引用

		<!-- json -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-lgpl</artifactId>
			<version>1.8.1</version>
		</dependency>

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-lgpl</artifactId>
			<version>1.8.1</version>
		</dependency>

 

先修改之前的helloworld.jsp,增加客户端json格式的数据输入。

	var cfg = 	{
	    type: 'POST', 
	    data: JSON.stringify({userName:'winzip',password:'password',mobileNO:'13818881888'}), 
	    dataType: 'json',
	    contentType:'application/json;charset=UTF-8',	    
	    success: function(result) { 
	        alert(result.success); 
	    } 
	};

function doTestJson(actionName){
	cfg.url = actionName;
	$.ajax(cfg);
}

 根据前面的分析,在spring mvc中解析输入为json格式的数据有两种方式
1:使用@RequestBody来设置输入

    @RequestMapping("/json1")
    @ResponseBody
	public JsonResult testJson1(@RequestBody User u){
    	log.info("get json input from request body annotation");
    	log.info(u.getUserName());
    	return new JsonResult(true,"return ok");
}

 2:使用HttpEntity来实现输入绑定

    @RequestMapping("/json2")    
    public ResponseEntity<JsonResult> testJson2(HttpEntity<User> u){
    	log.info("get json input from HttpEntity annotation");
    	log.info(u.getBody().getUserName());
    	ResponseEntity<JsonResult> responseResult = new ResponseEntity<JsonResult>( new JsonResult(true,"return ok"),HttpStatus.OK);
    	return responseResult;
}

 

Json格式的输出也对应有两种方式
1:使用@responseBody来设置输出内容为context body
2:返回值设置为ResponseEntity<?>类型,以返回context body
另外,第三种方式是使用ContentNegotiatingViewResolver来设置输出为json格式,需要修改servlet context配置文件如下

	<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="order" value="1" />
		<property name="mediaTypes">
			<map>
				<entry key="json" value="application/json" />
			</map>
		</property>
		<property name="defaultViews">
			<list>
				<bean
					class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
			</list>
		</property>
		<property name="ignoreAcceptHeader" value="true" />
	</bean>

 但这种格式的输出会返回{model类名:{内容}} 的json格式,
例如,以下代码

    @RequestMapping("/json3.json")
    public JsonResult testJson3(@RequestBody User u){
    	log.info("handle json output from ContentNegotiatingViewResolver");
    	return new JsonResult(true,"return ok");
    }

 

期望的返回是 {success:true,message:”return ok”};
但实际返回的却是 {"jsonResult":{"success":true,"msg":"return ok"}}
原因是MappingJacksonJsonView中对返回值的处理未考虑modelMap中只有一个值的情况,直接是按照mapName:{mapResult}的格式来返回数据的。
修改方法,重载MappingJacksonJsonView类并重写filterModel方法如下

    protected Object filterModel(Map<String, Object> model) {  
        Map<?, ?> result = (Map<?, ?>) super.filterModel(model);  
        if (result.size() == 1) {  
            return result.values().iterator().next();  
        } else {  
            return result;  
        }  
    }  

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值