java中json传输数据乱码问题处理方法:(引荐:java视频教程)
1、对参数先举行ISO-8859-1编码,再以utf-8解码
@RequestMapping(method=RequestMethod.GET) @ResponseBody public ResponseEntity<ResultModel> searchBorrows(String borrow_name) throws UnsupportedEncodingException{ //处理乱码问题 System.out.println("编码前===:"+borrow_name);//乱码 String borrowName=new String(borrow_name.getBytes("ISO-8859-1"),"utf-8"); System.out.println("编码后:========="+borrowName);//平常
2、假如是平常的要求,(非ajax的json**要求乱码**,直接在web.xml中设置中文过滤器) 以下:
<filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern><!-- 对要求项面前目今一切资本举行过滤--> </filter-mapping>
在没有用springmvc时,也可增加该句处理post要求的乱码问题:request.setCharacterEncoding(“UTF-8”);
注: tomcat8已把get要求的乱码问题处理了,tomcat7还需本身处理
3、ajax的json数据乱码
在项目中偶然须要异步要求,能够在springmvc设置文件中,在注解完成的适配器和映射器标签中增加两个转换器即可,可处理对json数据要乞降相应的乱码(假如tomcat编码没改,依旧存在乱码问题,一切涌现乱码是多方面的的)。
以下是设置spinngmvc中带的两个json转换器,完成处理json数据要乞降相应乱码问题。
<!-- 注解的适配器和映射器 --> <mvc:annotation-driven> <mvc:message-converters> <!--@ResponseBody 中文相应乱码 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value> text/plain;charset=UTF-8 </value> <value> text/html;charset=UTF-8 </value> <value> application/json;charset=UTF-8 </value> <value> application/x-www-form-urlencoded;charset=UTF-8 </value> </list> </property> </bean> <!-- JSON中文要求乱码及处理 HttpMediaTypeNotAcceptableException: Could not find acceptable representation 非常信息--> <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value> application/json;charset=UTF-8 </value> <value> application/x-www-form-urlencoded;charset=UTF-8 </value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
更多java学问请关注java基础教程栏目。
以上就是java中json传输数据乱码问题的细致内容,更多请关注ki4网别的相干文章!