SpringMvc中对json数据的处理

版权声明:如需转载,请注明出处! https://blog.csdn.net/qq_41172416/article/details/83653811

1、使用@ResponseBody实现数据输出

      @ResponseBody的作用:

      将标注此注解的处理方法的返回值结果直接写入HTTP  ResponseBody (Response对象的body数据区)中。

注意:使用下面代码时,需要在工程中引入阿里巴巴的fastjson-1.2.13jar

/**
	 * 查看用户
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/view",method=RequestMethod.GET)
	@ResponseBody
	public Object View(@RequestParam String id){
		User user=null;
		if(StringUtils.isNullOrEmpty(id)){
			return "nodata";
		}else{
			try {
				 user=userService.getUserById(id);
			} catch (Exception e) {
				e.printStackTrace();
				return "failed";
			}
		}
		return JSONArray.toJSONString(user);
	}

 2、解决 JSON 数据传递的中文乱码问题

 

 出现乱码的原因:

控制器的处理方法采用@ResponseBody注解向前台页面以JSON格式进行数据传递的时候,若返回值是中文,则会出现乱码,原因是消息转换器 (org.springframework.http.converter.StringHttpMessageConverter)中固定了转换字符编码,如下所示。

public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {

	public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
    
        //......省略部分代码
}

 两种解决办法:

       1、在控制器处理方法上的@RequestMapping注解中配置produces

       /**
	 * 查看用户
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/view",method=RequestMethod.GET,produces={"application/json;charset=utf-8"})
	@ResponseBody
	public Object View(@RequestParam String id){
		User user=null;
		if(StringUtils.isNullOrEmpty(id)){
			return "nodata";
		}else{
			try {
				 user=userService.getUserById(id);
			} catch (Exception e) {
				e.printStackTrace();
				return "failed";
			}
		}
		return JSONArray.toJSONString(user);
	}

       2、在springmvc-servlet.xml中配置StringHttpMessageConverter(消息转换器)

<mvc:annotation-driven>
	<mvc:message-converters>
    		<bean class="org.springframework.http.converter.StringHttpMessageConverter">
    			<property name="supportedMediaTypes">
    				<list>
    					<value>application/json;charset=utf-8</value>
    				</list>
    			</property>
    		</bean>
    	</mvc:message-converters>
</mvc:annotation-driven>

3、解决JSON 数据传递的日期格式问题

 

两种解决办法:

       1、在pojo中添加注解方式: @JSONField(format="yyyy-MM-dd")

package com.bdqn.pojo;

import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

import com.alibaba.fastjson.annotation.JSONField;

public class User {
	
        @JSONField(format="yyyy-MM-dd")
	private Date birthday;  //出生日期

	@JSONField(format="yyyy-MM-dd hh:mm:ss")
	private Date creationDate; //创建时间
	
         //......省略部分代码
	
}

添加之后的效果:

       2、在springmvc-servlet.xml中配置 FastJsonHttpMessageConverter (消息转换器)

<mvc:annotation-driven>
	<mvc:message-converters>
    		<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                        <!--被支持的媒体类型 -->
    			<property name="supportedMediaTypes">
    				<list>
    					<value>text/html;charset=utf-8</value>
    					<value>application/json</value>
    				</list>
    			</property>
    			<property name="features">
    				<list>
                                        <!--输出 Date的日期转换器 -->
    					<value>WriteDateUseDateFormat</value>
    				</list>
    			</property>
    		</bean>
    	</mvc:message-converters>
</mvc:annotation-driven>

在进行以下操作之前,先注释掉刚才pojo中的 @JSONField 注解

由于,以上配置中设置了supportedMediaTypes属性,因此,需要修改控制器的方法,直接返回user对象即可

       /**
	 * 查看用户
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/view",method=RequestMethod.GET,produces={"application/json;charset=utf-8"})
	@ResponseBody
	public Object View(@RequestParam String id){
		User user=null;
		if(StringUtils.isNullOrEmpty(id)){
			return "nodata";
		}else{
			try {
				 user=userService.getUserById(id);
			} catch (Exception e) {
				e.printStackTrace();
				return "failed";
			}
		}
		return user; //此时不需要手动把user对象转成Json,直接返回对象即可
	}

效果演示:

 下面我们解决出生日期格式问题

            在pojo中添加注解 :@JSONField(format="yyyy-MM-dd")

package com.bdqn.pojo;

import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

import com.alibaba.fastjson.annotation.JSONField;

public class User {
	
        @JSONField(format="yyyy-MM-dd")
	private Date birthday;  //出生日期

         //......省略部分代码
	
}

效果演示:

猜你喜欢

转载自blog.csdn.net/qq_41172416/article/details/83653811
今日推荐