在web服务器配置中直接加上下面的过滤处理
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式。采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
json转换为js对象
//将json转json
var obj =JSON.parse(json);
console.log(obj);
js对象转换为json字符串
//将js转换为json
var json= JSON.stringify(people);
console.log(json);
<%--
Created by IntelliJ IDEA.
User: 塔塔
Date: 2022/7/25
Time: 20:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
导包
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.13.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.13.3version>
dependency>
Jackson转换java和json数据格式
package com.spring.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author panglili
* @create 2022-07-25-20:36
*/
@Controller
public class JsonController {
//produces = "application/json;charset=utf-8"
//json提供的数据编码处理
@ResponseBody
@RequestMapping(value = "/json",produces = "application/json;charset=utf-8")
public String json1() throws JsonProcessingException {
//jsckson 提供的将一个json字符与java对象自动转换的类
ObjectMapper mapper = new ObjectMapper();
//创建对象
User user=new User("小镇",19,"男");
//交给mapper转换
String s = mapper.writeValueAsString(user);
return s;
}
}
json处理乱码还有一种方式,直接配置在mvc中,不需要每个请求上面都去搞
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
bean>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
导包
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.72version>
dependency>
直接调用它提供的JSON对象
@RequestMapping("/j2")
@ResponseBody
public String json(){
User user=new User("小镇",19,"男");
String s = JSON.toJSONString(user);
return s;
}