JSON(JavaScript Object Notation,JS标记对象),一种轻量级的数据交换格式
采用完全独立于编程语言的文本格式来存储和表示数据
易于人阅读和编写,也易于机器解析和生成,有效地提升网络传输效率
JSON作为理想的前后端数据交换的数据格式
? JSON语法格式
? JSON键值对是用来保存JavaScript对象的一种方式,键和值都用双引号“ ”包裹,中间冒号:分隔表示方法如下:
{"name":"zhangsan"}
{"age":"3"}
{"sex":"男"}
var obj = {a:‘Hello‘,b:‘world‘}; //这是一个对象,注意键名也是可以用引号包裹的
var json = ‘{"a":"Hello","b":"world"}‘; //这是一个JSON字符串
var json = ‘{"a":"Hello","b":"world"}‘;
var obj = JSON.parse(json);
//obj = {a:‘Hello‘,b:‘world‘}
var obj = {a:‘Hello‘,b:‘world‘};
var json = JSON.stringify(obj);
// json = ‘{"a":"Hello","b":"world"}‘
常用的json解析工具:
使用时需要导入相应的jar包,这里使用Jackson
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springmvc.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.spong.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Controller类
@Controller
public class UserController {
@RequestMapping("/json")
@ResponseBody //表示这个方法直接给前端返回一个字符串,不会走视图解析器
public String jsonTest() throws JsonProcessingException {
//使用Jackson下的ObjectMapper转换
ObjectMapper mapper = new ObjectMapper();
User user = new User(1, "zhangsan", "女");
String str = mapper.writeValueAsString(user);
return str;
}
}
启动Tomcat后访问到http://localhost:8080/json 后显示为如下:
{"id": 1,"name": "zhangsan","sex": "?"}
可以看到返回到页面的数据以及是JSON字符串了
user.toString()做对比:
User{id=1, name=‘zhangsan‘, sex=‘?‘}
不过这里存在乱码问题,可以在springmvc.xml文件中设置编码格式
<mvc:annotation-driven>
<!--json格式乱码处理-->
<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("/json2")
@ResponseBody //表示这个方法直接给前端返回一个字符串,不会走视图解析器
public String json2() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Date date = new Date();
//mapper.writeValueAsString(date); 默认写出的是时间戳的形式
//1.自定义时间格式
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format1 = format.format(date);
//2.设置ObjectMapper关闭写出时间戳的方式,再自定义其格式
mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS,false);
mapper.setDateFormat(format);
return mapper.writeValueAsString(date);
}
public class JsonUtil {
//只传入一个对象时,默认给一个日期格式
//重载方法,实现方法的复用
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
//dateFormat可自定义输入日期格式
public static String getJson(Object object,String dateFormat){
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS,false);
mapper.setDateFormat(format);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
之后可简化Controller类如下:
@Controller
public class UserController {
@RequestMapping("/json1")
@ResponseBody //表示这个方法直接给前端返回一个字符串,不会走视图解析器
public String jsonTest() throws JsonProcessingException {
User user = new User(1, "zhangsan", "女");
return JsonUtil.getJson(user);
}
@RequestMapping("/json2")
@ResponseBody //表示这个方法直接给前端返回字符串,不会走视图解析器
public String json2() throws JsonProcessingException {
Date date = new Date();
return JsonUtil.getJson(date,"yyyy-MM-dd HH:mm:ss");
}
}
fastjson.jar是阿里开发的一款专门用于JAVA开发的包,可以方便地实现json对象和JavaBean对象的转换等
? fastJson的pom依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
fastjson三个主要的类:
【JSONObject 代表json对象】
【JSONArray代表json对象数组】
【JSON代表JSONObject和JSONArray的转换】
相关使用:
List<User> userList = new ArrayList<User>();
User user1 = new User(1, "张1三", "男");
User user2 = new User(2, "张2三", "男");
User user3 = new User(3, "张3三", "男");
User user4 = new User(4, "张4三", "男");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
//Java对象 转 JSON字符串
String s1 = JSON.toJSONString(userList);
String s2 = JSON.toJSONString(user1);
//JSON字符串 转 Java对象
User jsUser = JSON.parseObject(s2, User.class);
//Java对象 转 JSON对象
JSONObject jsonObject = (JSONObject) JSON.toJSON(user1);
//JSON对象 转 Java对象
User user = JSON.toJavaObject(jsonObject, User.class);
Json对象
最显著的特征:对象的值可以用 “对象.属性” 进行访问;
typeOf(json对象) ===> Object类型
例子如下:
var person={"name":"shily","sex":"女","age":"23"}//json对象console.log(person);
console.log(person.name);console.log(typeof person);
输出结果:
Json字符串(所谓字符串:单引号或者双引号引起来)
var person=‘{"name":"shily","sex":"女","age":"23"}‘;//json字符串
console.log(person)
console.log(person.name)
console.log(typeof person)
输出结果:
原文:https://www.cnblogs.com/spang/p/13599273.html