标签:script col text factor defaults fas struct drive code
0、为什么火?有什么用?
前后端分离最重要的是什么?
就是数据传输
而Json就是一个极为优秀的前后端传输数据的格式或者说工具
1、概念
var obj = {a: ‘Hello‘, b: ‘World‘}; //这是一个对象,注意键名也是可以使用引号包裹的
var json = ‘{"a": "Hello", "b": "World"}‘; //这是一个 JSON 字符串,本质是一个字符串
2、用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var user = {
name : "冰冰",
age : 17
}
console.log(user);
console.log("=========================================")
//把对象转换为json
var json = JSON.stringify(user);
console.log(json);
//把json转换为对象
var obj = JSON.parse(‘{"name":"zhangsan", "age":17}‘);
console.log(obj);
</script>
</head>
<body>
</body>
</html>
1、导入相关依赖Jackson或者fastJson
<dependencies>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
2、把包导入到lib
不然会报404
3、编写工具类
一个比较简单的工具类
package com.bing.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
/**
* @author zhangbingbing
* @version 1.0
* @date 2020/5/28 12:07
*/
public class JsonUtil {
//自己编写工具类
/**
*
* @param object : 我们要转换的类型
* @param format : 格式,一般用于日期
* @return
*/
public static String getJson(Object object, String format) {
//创建一个处理java对象的mapper
ObjectMapper mapper = new ObjectMapper();
//把默认格式关了
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//设定日期格式
SimpleDateFormat sdf = new SimpleDateFormat(format);
//用mapper映射来设置日期格式
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
//重载一个方法
public static String getJson(Object object) {
return getJson(object, "yyyy-MM-dd HH:mm:ss");
}
}
4、测试
亲测可以
package com.bing.controller;
import com.bing.pojo.User;
import com.bing.utils.JsonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* @author zhangbingbing
* @version 1.0
* @date 2020/5/28 11:55
*/
//@RestController //表示下面的所有方法都不走视图过滤器,直接返回到页面
@Controller
public class TestJson {
@ResponseBody //这个注解有啥用:直接让下面的方法不走视图过滤器,直接返回字符串到页面上
@RequestMapping("/t1")
public String test01() throws JsonProcessingException {
//在Jackson中我们用的最多的ObjectMappering
ObjectMapper mapper = new ObjectMapper();
User user = new User("冰冰", 17, "boy");
return mapper.writeValueAsString(user);
}
@ResponseBody //这个注解有啥用:直接让下面的方法不走视图过滤器,直接返回字符串到页面上
@RequestMapping("/t2")
public String test02() throws JsonProcessingException {
//在Jackson中我们用的最多的ObjectMappering
User user = new User("冰冰2号", 12, "girl");
return JsonUtil.getJson(user);
}
@ResponseBody //这个注解有啥用:直接让下面的方法不走视图过滤器,直接返回字符串到页面上
@RequestMapping("/t3")
public String test03() throws JsonProcessingException {
//在Jackson中我们用的最多的ObjectMappering
Date date = new Date();
return JsonUtil.getJson(date);
}
}
5、遇到的问题
乱码问题
在pringmvc-servlet.xml中配置解决乱码问题
<!-- 乱码问题统一解决-->
<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>
后端设置编码
@RequestMapping("/a1")
public void ajax(String name, HttpServletResponse response) throws IOException {
System.out.println("找到了资源!");
System.out.println("param:name-->" + name);
response.setContentType("text/html;charset=utf-8");
Map<String, Object> map = new HashMap<String, Object>();
if ("bingbing".equals(name)) {
map.put("userExist", true);
map.put("msg", "用户名已存在!");
} else {
map.put("userExist", false);
map.put("msg", "用户名可用!");
}
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getWriter(), map);
}
<script>
function a1() {
$.post("${pageContext.request.contextPath}/a1", {name:$("#str").val()}, function (data) {
alert(data);
var mag = $("#msg");
if (data.userExist) {
mag.css("color", "red");
mag.html(data.msg);
} else {
mag.css("color", "green");
mag.html(data.msg);
}
}, "json")
}
</script>
标签:script col text factor defaults fas struct drive code
原文地址:https://www.cnblogs.com/bingstudy/p/13192582.html