其他分享
首页 > 其他分享> > day22-Jackson

day22-Jackson

作者:互联网

day22-Jackson

对象类型数据返回

什么是JSON?

在 JavaScript 语言中,一切都是对象。因此,任何JavaScript 支持的类型都可以通过 JSON 来表示,例如字符串、数字、对象、数组等。看看他的要求和语法格式:

JSON 键值对是用来保存 JavaScript 对象的一种方式,和 JavaScript 对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 “” 包裹,使用冒号 : 分隔,然后紧接着值:

{"name": "QinJiang"}
{"age": "3"}
{"sex": "男"}

很多人搞不清楚 JSON 和 JavaScript 对象的关系,甚至连谁是谁都不清楚。其实,可以这么理解:

JSON 是 JavaScript 对象的字符串表示法,它使用文本表示一个 JS 对象的信息,本质是一个字符串。

var obj = {a: 'Hello', b: 'World'}; //这是一个对象,注意键名也是可以使用引号包裹的
var json = '{"a": "Hello", "b": "World"}'; //这是一个 JSON 字符串,本质是一个字符串

JSON 和 JavaScript 对象互转

要实现从JSON字符串转换为JavaScript 对象,使用 JSON.parse() 方法:

var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//结果是 {a: 'Hello', b: 'World'}

要实现从JavaScript 对象转换为JSON字符串,使用 JSON.stringify() 方法:

var json = JSON.stringify({a: 'Hello', b: 'World'});
//结果是 '{"a": "Hello", "b": "World"}'

新建一个项目:

1.导入json解析器jackson的jar包

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.8</version>
</dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
    </dependencies>

2.配置springmvc的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">

   <!--1.注册servlet-->
   <servlet>
       <servlet-name>SpringMVC</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
       <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>

   <!--所有请求都会被springmvc拦截 -->
   <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>

3.编写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
       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.sjh.controller"/>

   <!-- 视图解析器 -->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
         id="internalResourceViewResolver">
       <!-- 前缀 -->
       <property name="prefix" value="/WEB-INF/jsp/" />
       <!-- 后缀 -->
       <property name="suffix" value=".jsp" />
   </bean>

</beans>

4.编写User实体类

package com.sjh.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    String name;
    String sex;
    String password;
}

5.解决json乱码问题,放到springmvc-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>

6.编写测试类

package com.sjh.controller;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.sjh.bean.User;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class jsonTest {    @RequestMapping("aaa")    @ResponseBody    public String json() throws JsonProcessingException {        //创建一个jackson对象映射器,用来解析数据        ObjectMapper objectMapper = new ObjectMapper();        User user = new User("史佳豪","男","11111");        String s = objectMapper.writeValueAsString(user);//以字符串形式输出对象        return s;    }}

结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GNH6c0sc-1627444483402)(https://i.loli.net/2021/07/27/Ts2P7HyuZC1XUow.png)]

@RestController

当一个类中所有的方法我们都像让它们返回jaso格式的字符串而不让视图解析器去解析,那么就可以直接在类上用@RestController注解,它就如同@Controller+@ResponseBody

@RestControllerpublic class UserController {   //produces:指定响应体返回类型和编码   @RequestMapping(value = "/json1")   public String json1() throws JsonProcessingException {       //创建一个jackson的对象映射器,用来解析数据       ObjectMapper mapper = new ObjectMapper();       //创建一个对象       User user = new User("秦疆1号", 3, "男");       //将我们的对象解析成为json格式       String str = mapper.writeValueAsString(user);       //由于@ResponseBody注解,这里会将str转成json格式返回;十分方便       return str;  }}

重点:

1.创建jackson对象 :ObjectMapper mapper =new ObjectMapper();

2.将其他类型转化为json类型字符串:String s=mapper.writeValeAsString(user);

集合类型数据转换

其他的配置与上面相同,新建一个方法

   @RequestMapping("bbb")    public String json1() throws JsonProcessingException {        //创建一个jackson对象映射器,用来解析数据        ObjectMapper objectMapper = new ObjectMapper();        ArrayList<User> users = new ArrayList<>();        User user = new User("史佳豪","男","11111");        User user1 = new User("史佳豪","男","11111");        User user2 = new User("史佳豪","男","11111");        User user3 = new User("史佳豪","男","11111");        users.add(user);        users.add(user1);        users.add(user2);        users.add(user3);        String s = objectMapper.writeValueAsString(users);//以字符串形式输出对象        return s;    }

运行查看返回结果:

[]:包着的是集合

{}:代表对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EiUNYzQW-1627444483405)(https://i.loli.net/2021/07/27/UBxfK4pu5X26syw.png)]

时间类型数据转换

方式一:自定义时间格式

    @RequestMapping("time")    public String json2() throws JsonProcessingException {        //创建一个jackson对象映射器,用来解析数据        ObjectMapper objectMapper = new ObjectMapper();        Date date = new Date();        //定义输出时间格式规范        SimpleDateFormat stf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss" );        //转换获取时间        String format = stf.format(date);        String s = objectMapper.writeValueAsString(format);//以字符串形式输出对象        return s;    }

image-20210727115247307

方式二:使用mapper,不使用时间戳的方式

@RequestMapping("/json4")public String json4() throws JsonProcessingException {   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;}

抽取json转换工具类

package com.sjh.utils;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;import java.text.SimpleDateFormat;public class JsonUtils {    public static  String getJson(Object o){        return getJson(o,"yyyy-MM-dd hh:mm:ss");    }    public static String getJson(Object o, String spf){        //创建Json转换对象        ObjectMapper objectMapper = new ObjectMapper();        //不使用时间差的方式        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);        //规范时间输出样式        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(spf);        //指定日期格式         objectMapper.setDateFormat(simpleDateFormat);        try {            return objectMapper.writeValueAsString(o);        } catch (JsonProcessingException e) {            e.printStackTrace();        }        return null;    }}

测试

package com.sjh.controller;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.sjh.bean.User;import com.sjh.utils.JsonUtils;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;@RestControllerpublic class jsonTest {    @RequestMapping("aaa")    public String json() throws JsonProcessingException {        //创建一个jackson对象映射器,用来解析数据        ObjectMapper objectMapper = new ObjectMapper();        User user = new User("史佳豪","男","11111");        String s = objectMapper.writeValueAsString(user);//以字符串形式输出对象        return s;    }    @RequestMapping("bbb")    public String json1() throws JsonProcessingException {        //创建一个jackson对象映射器,用来解析数据        ObjectMapper objectMapper = new ObjectMapper();        ArrayList<User> users = new ArrayList<>();        User user = new User("史佳豪","男","11111");        User user1 = new User("史佳豪","男","11111");        User user2 = new User("史佳豪","男","11111");        User user3 = new User("史佳豪","男","11111");        users.add(user);        users.add(user1);        users.add(user2);        users.add(user3);        String s = objectMapper.writeValueAsString(users);//以字符串形式输出对象        return s;    }    @RequestMapping("time")    public String json2() throws JsonProcessingException {        Date date = new Date();        String json = JsonUtils.getJson(date);        return json;    }}

用jaso工具输出集合类

  @RequestMapping("bbb")    public String json1() throws JsonProcessingException {        ArrayList<User> users = new ArrayList<>();        User user = new User("史佳豪","男","11111");        User user1 = new User("史佳豪","男","11111");        User user2 = new User("史佳豪","男","11111");        User user3 = new User("史佳豪","男","11111");        users.add(user);        users.add(user1);        users.add(user2);        users.add(user3);        String json = JsonUtils.getJson(users);//以字符串形式输出对象        return json;    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-23qVWCLO-1627444483412)(https://i.loli.net/2021/07/27/luA43nehZ8DYLQg.png)]

成功

标签:Jackson,String,day22,User,import,new,ObjectMapper,users
来源: https://blog.csdn.net/pinganaaa/article/details/119176432