在 JavaScript 语言中,一切都是对象。因此,任何JavaScript 支持的类型都可以通过 JSON 来表示,例如字符串、数字、对象、数组等。看看他的要求和语法格式:
-
对象表示为键值对,数据由逗号分隔
-
花括号保存对象
-
方括号保存数组
难点:JSON 和 JavaScript 对象的关系
在fastjson中比较常见,
JSON 是 JavaScript 对象的字符串表示法,它使用文本表示一个 JS 对象的信息,本质是一个字符串。
JS对象:
{a: 'Hello', b: 'World'}
JSON:
'{"a": "Hello", "b": "World"}'
在JS中互相可以转化:
从JSON字符串转换为JavaScript 对象:
let obj = JSON.parse('{"a": "Hello", "b": "World"}')
从JavaScript 对象转换为JSON字符串
var json = JSON.stringify({a: 'Hello', b: 'World'})
看代码:
<script type="text/javascript">
let a={
name:"秦将",
age:3,
sex:"男"
}
// 对象转JSON
let b=JSON.stringify(a)
console.log(b)
// JSON转对象
let c=JSON.parse(b)
console.log(c)
</script>
结果:
可以看到上面的是JSON,下面的是JS对象。
接下来我们将它联合进SpringMVC中。
首先配置pom
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
</dependency>
版本你自己选择
接下来:
web.xml不需要变
还是关联SpringMVC配置文件,和防止乱码。
<?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">
<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>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
然后SpringMVC的配置文件也不需要改。
<?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
http://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">
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.yi.controller"/>
<!-- 让Spring MVC不处理静态资源 如MP3、MP4-->
<mvc:default-servlet-handler />
<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>
<!--
支持mvc注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而annotation-driven配置帮助我们自动完成上述两个实例的注入。
-->
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
既然设计对象的前后端传递,我们先建立一个实体类。
这里需要配置pom.xml.添加
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String id;
private String name;
private int age;
}
有了上面的注解后,我们不需要建立带参构造器,也能使用带参构造器。
但是后面用的时候idea会爆红,但是不影响结果,可能是idea的版本问题,我的是2020.1版本。
ok,下一步。
我这里直接说最简单的一种方法。
编写我们的控制层,也就是Controller。
这里我再说一点,之前的controller返回的是一个视图,现在我们要返回一个JSON,也就是说不需要走视图控制器了。
我们类上面的注解就需要改变(
@RestController
)。
当然使用这种注解,我们整个类方法都不能返回视图层了,只能用作前端交互数据。
如果你这个类既想有返回视图层的方法,又想有返回JSON的方法,那么:
类注解还是用:@Controller
方法上面依旧是@RequestMapping
在下面加上
@ResponseBody就可以让这个类跳过视图解析器,从而返回JSON。
@RestController
public class json {
@RequestMapping(value = "/q1",produces = "application/json;charset=utf-8")
public String text01() throws JsonProcessingException {
ObjectMapper mapper=new ObjectMapper();
User user0=new User("1","撒",10);
User user1=new User("2","撒",10);
User user2=new User("3","撒",10);
User user3=new User("4","撒",10);
List<User> user=new ArrayList();
user.add(user0);
user.add(user1);
user.add(user2);
user.add(user3);
String str=mapper.writeValueAsString(user);
return str;
}
}
products是防止乱码,我不知道我的配置xml为什莫没用,只有这种方式可以防止乱码。
当然value的值依然是用户输入的路径。
看结果。
我们讲java对象转换成了JSON。
接下来我们来说一下如何用JSON输出时间,这是传统的Java获取时间。
Date date=new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String a=simpleDateFormat.format(date);
System.out.println(a);
ObjectMapper mapper = new ObjectMapper();
//不使用时间戳的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定义日期格式对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//指定日期格式
mapper.setDateFormat(sdf);
Date date = new Date();
String str = mapper.writeValueAsString(date);
return str;
可以看到好像变复杂了,不过我们可以封装一下,参考写开源代码的格式,写一个工具类方法。
public static String getJson(Object object) {
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJson(Object object,String dateFormat) {
ObjectMapper mapper = new ObjectMapper();
//不使用时间差的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定义日期格式对象
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//指定日期格式
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
想自定义格式就把格式参数带上。
然后想输出时间就这莫一行代码了。
public String text02() throws JsonProcessingException {
return JsonUtils.getJson(new Date());
}
最后说一下FastJson
首先需要导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
主要三个类:
JSONObject 代表 json 对象
JSONArray 代表 json 对象数组
JSON代表 JSONObject和JSONArray的转化
其使用比较方便。
这里会用就行:
public static void main(String[] args) {
List<User> user=new ArrayList<User>();
User user1=new User("001","请问",10);
User user2=new User("002","阿城市",10);
User user3=new User("003","双方都是",10);
User user4=new User("004","算法的",10);
user.add(user1);
user.add(user2);
user.add(user3);
user.add(user4);
// Java对象 转 JSON字符串
String str= JSON.toJSONString(user1);
System.out.println(str);
// JSON字符串 转 Java对象
String str0=JSON.toJSONString(user1);
JSONObject user5=JSON.parseObject(str0);
System.out.println(user5);
// Java对象 转 JSON对象
JSONObject jsonObject= (JSONObject) JSON.toJSON(user2);
System.out.println(jsonObject);
// JSON对象 转 Java对象
User user6=JSON.toJavaObject(jsonObject,User.class);
System.out.println(user6);
}