JSON和JS对象的互相转换
- JSON.stringfy() obj -> json
- JSON.parse() json -> obj
<script>
let user = {
name: "老王",
age: 18,
sex: "男"
}
// 对象转为 json 字符串
objToJson = JSON.stringify(user)
// json字符串转换为对象
JsonToObj = JSON.parse(objToJson)
console.log(user)
console.log("-----------------")
console.log(objToJson)
console.log("-----------------")
console.log(JsonToObj)
</script>
Controller返回JSON格式数据
使用工具jackson
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
环境配置
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>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</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-servlet.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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.wcy.controller"/>
<!-- 让Spring MVC不处理静态资源 -->
<mvc:default-servlet-handler/>
<!-- 注册注解驱动 -->
<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>
对象转为Json
编写一个实体类
使用lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
int id;
String name;
int age;
}
编写controller
@Controller
public class JSONController {
@RequestMapping("/json/01")
@ResponseBody //使用该注解使返回的字符串不经过视图解析,仅仅是一个普通的字符串
public String Test() throws JsonProcessingException {
// objectMapper 用来将对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper();
User user = new User(1, "老王", 18);
// 将对象转换为json字符串
return objectMapper.writeValueAsString(user);
}
}
配置tomcat并测试
Chrome中FeHelper插件可以自动解析json字符串
可以看到成功返回了json字符串,不过有乱码,需要设置编码类型和返回类型
@RequestMapping(value = "/json/01", produces = "application/json;charset=utf-8")
重新测试,乱码解决
{
"id": 1,
"name": "老王",
"age": 18
}
json乱码处理
通用的json乱码解决方法,可避免每次都要重复配置@ResquestMapping
在springmvc的配置文件上添加一段消息StringHttpMessageConverter转换配置!
<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>
返回字符串可以在类上使用RestController注解,这样改类中的每一个方法返回的都是字符串
@RestController
public class JSONController {
@RequestMapping("/json/01")
@ResponseBody //使用该注解使返回的字符串不经过视图解析,仅仅是一个普通的字符串
public String Test() throws JsonProcessingException {
// objectMapper 用来将对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper();
User user = new User(1, "老王", 18);
// 将对象转换为json字符串
return objectMapper.writeValueAsString(user);
}
}
集合转为JSON
@RequestMapping("/json/02")
public String Test02() throws JsonProcessingException {
// objectMapper 用来将对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper();
User user1 = new User(1, "老王", 18);
User user2 = new User(2, "老王", 18);
User user3 = new User(3, "老王", 18);
User user4 = new User(4, "老王", 18);
ArrayList<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
// 将对象转换为json字符串
return objectMapper.writeValueAsString(userList);
}
多个json字符串是用[]包裹起来的
[
{
"id": 1,
"name": "老王",
"age": 18
},
{
"id": 2,
"name": "老王",
"age": 18
},
{
"id": 3,
"name": "老王",
"age": 18
},
{
"id": 4,
"name": "老王",
"age": 18
}
]
时间对象输出
@RequestMapping("/json/03")
public String Test03() throws JsonProcessingException {
// objectMapper 用来将对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();
// 将对象转换为json字符串
return objectMapper.writeValueAsString(date);
}
默认是时间戳的形式输出
可以使用SimpleDateFormat格式化
@RequestMapping("/json/03")
public String Test03() throws JsonProcessingException {
// objectMapper 用来将对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String formatDate = simpleDateFormat.format(date);
// 将对象转换为json字符串
return objectMapper.writeValueAsString(formatDate);
}
或者将SimpleDateFormat对象传递给ObjectMapper
@RequestMapping("/json/03")
public String Test03() throws JsonProcessingException {
// objectMapper 用来将对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
objectMapper.setDateFormat(simpleDateFormat);
// 将对象转换为json字符串
return objectMapper.writeValueAsString(date);
}
基于以上操作可以将转换过程封装为一个工具类
public class JSONUtil {
public static String toJSON(Object o) throws JsonProcessingException {
return toJSON(o, "yyyy-MM-dd hh:mm:ss");
}
public static String toJSON(Object o, String dateFormatPatten) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat(dateFormatPatten));
return objectMapper.writeValueAsString(o);
}
}
极大简化代码
@RequestMapping("/json/04")
public String Test04() throws JsonProcessingException {
return JSONUtil.toJSON(new Date());
}
使用FastJson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
public class FastJsonTest {
public static void main(String[] args) {
//创建一个对象
User user1 = new User(1, "老王", 18);
User user2 = new User(2, "老王", 18);
User user3 = new User(3, "老王", 18);
User user4 = new User(4, "老王", 18);
List<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
System.out.println("*******Java对象 转 JSON字符串*******");
String str1 = JSON.toJSONString(list);
System.out.println("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user1);
System.out.println("JSON.toJSONString(user1)==>"+str2);
System.out.println("\n****** JSON字符串 转 Java对象*******");
User jp_user1=JSON.parseObject(str2,User.class);
System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);
System.out.println("\n****** Java对象 转 JSON对象 ******");
JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));
System.out.println("\n****** JSON对象 转 Java对象 ******");
User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
}
}
结果
*******Java对象 转 JSON字符串*******
JSON.toJSONString(list)==>[{"age":18,"id":1,"name":"老王"},{"age":18,"id":2,"name":"老王"},{"age":18,"id":3,"name":"老王"},{"age":18,"id":4,"name":"老王"}]
JSON.toJSONString(user1)==>{"age":18,"id":1,"name":"老王"}
****** JSON字符串 转 Java对象*******
JSON.parseObject(str2,User.class)==>User(id=1, name=老王, age=18)
****** Java对象 转 JSON对象 ******
(JSONObject) JSON.toJSON(user2)==>老王
****** JSON对象 转 Java对象 ******
JSON.toJavaObject(jsonObject1, User.class)==>User(id=2, name=老王, age=18)