SpringMVC-07-JSON講解

7. JSON講解

前后端分離時代:

后端部署后端,提供接口,提供數(shù)據(jù);

前端獨立部署,負責(zé)渲染后端的數(shù)據(jù);

json誕生,作為前后端傳遞的格式!

什么是JSON?

  • JSON(Javascript Object Notation,JS對象標記),輕量級的數(shù)據(jù)交換格式;
  • 采用完全獨立于編程語言的文本格式來存儲和表示數(shù)據(jù);
  • 簡潔清晰的層次結(jié)構(gòu)
  • 易于人閱讀和編寫,也易于機器解析和生成;

在JavaScript語言中,一切都是對象。因此,任何JavaScript支持的類型都可以通過JSON來表示。

要求和語法格式:

  • 對象表示為鍵值對,數(shù)據(jù)由括號分隔
  • 花括號保存對象
  • 方括號保存數(shù)組

JSON鍵值對是用來保存JavaScript對象的一種方式,用雙引號包裹,使用冒號分隔。

JSON和JavaScript對象的關(guān)系:

  • JSON是JavaScript對象的字符串表示法,使用文本表示一個JS對象的信息,本質(zhì)是一個字符串。

    var obj={a:'hello',b:'world'};
    var json='{a:"hello",b:"world"}'
    

JSON和JS對象的互轉(zhuǎn)

  • JSON-->JS對象,JSON.parse()方法;

    var obj = JSON.parse(json);
    
  • JS對象-->JSON,JSON.stringify()方法;

    var json = JSON.stringify(user);
    

代碼測試步驟:

  1. 新建一個module,springmvc-05-json,添加web支持

  2. 在web目錄下新建一個jsontest.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script type="text/javascript">
            //編寫一個js對象 ES6支持let定義對象
            var user={
                name:"huba",
                age:3,
                sex:"男"
            }
            //js對象轉(zhuǎn)化為json對象
            var json = JSON.stringify(user);
            console.log(json);
            //console.log(user);
            //json轉(zhuǎn)化為js對象
            var obj = JSON.parse(json);
            console.log("========= ")
            console.log(obj);
        </script>
    </head>
    <body>
    
    </body>
    </html>
    

Controller返回JSON數(shù)據(jù)

  • Jackson是目前比較好的json解析工具

  • 首先需要導(dǎo)入它的jar包:

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.1</version>
    </dependency>
    
    
  • 配置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">
        <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
            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">
    
        <!--自動掃描包 讓指定包下的注解生效 由IOC容器統(tǒng)一管理-->
        <context:component-scan base-package="com.kuang.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>
    
  • 編寫一個User實體類,然后編寫測試Controller;

  • 這里我們需要兩個新東西,一個是@ResponseBody,一個是ObjectMapper對象;

    @Controller
    public class UserController {
        @RequestMapping("j1")
        @ResponseBody //表示不走視圖解析器
        public String json1() throws JsonProcessingException {
            //jackson的對象 ObjectMapper
            ObjectMapper objectMapper = new ObjectMapper();
    
            //創(chuàng)建對象
            User user = new User("胡巴1號", 3, "男");
    
            String s = objectMapper.writeValueAsString(user);
            return s;
        }
    }
    
  • 配置Tomcat,啟動測試一下!

  • 發(fā)現(xiàn)亂碼問題,我們需要設(shè)置他的編碼格式為ntf-8,以及它的返回類型;

  • 通過@RequestMapping的produces屬性來實現(xiàn)

    @RequestMapping(value = "j1",produces = "application/json;charset=utf-8")
    
  • 再次測試,亂碼問題解決!

代碼優(yōu)化

亂碼統(tǒng)一解決

我們可以在springmvc配置文件上添加一段消息StringHttpMessageConverter轉(zhuǎn)換配置!

<!--JSON亂碼問題配置-->
<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>

返回json字符串統(tǒng)一解決

如果要不走視圖解析器,兩種方法:

  1. 在方法上使用注解@ResponseBody
  2. 在類上使用注解@RestController
@RequestMapping("/j1")
@ResponseBody //表示不走視圖解析器
public String json1() throws JsonProcessingException {
    //jackson的對象 ObjectMapper
    ObjectMapper objectMapper = new ObjectMapper();

    //創(chuàng)建對象
    User user = new User("胡巴1號", 3, "男");

    String s = objectMapper.writeValueAsString(user);
    return s;
}

測試集合輸出

@RequestMapping("/j2")
@ResponseBody
public String json2() throws JsonProcessingException {

    ObjectMapper objectMapper = new ObjectMapper();

    List<User> userList=new ArrayList<User>();
    User user1 = new User("胡巴1號", 3, "男");
    User user2 = new User("胡巴2號", 4, "男");
    User user3 = new User("胡巴3號", 5, "男");

    userList.add(user1);
    userList.add(user2);
    userList.add(user3);

    String s = objectMapper.writeValueAsString(userList);
    return s;//合并成一句代碼 new ObjectMapper().writeValueAsString(userlist);
}

輸出時間對象

    @RequestMapping("/j3")
    @ResponseBody
    public String json3() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        //默認時間戳 timestamp
//        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        //第二種方法,使用ObjectMapper 關(guān)閉默認時間戳輸出
        objectMapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS,false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        Date date = new Date();
        String s = objectMapper.writeValueAsString(date);
        return s;
    }
}

抽取為工具類

如果要經(jīng)常使用的話,這樣是比較麻煩的,我們可以封裝到一個工具類中。

public class JsonUtils {
    public static String getJson(Object object){
        return getJson(object,"yyyy-MM-dd HH:mm:ss");
    }

    public static String getJson(Object object,String dateFormat){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS,false);
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        objectMapper.setDateFormat(sdf);

        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

FastJson

fastjson.jar是阿里開發(fā)的一款專門用于Java開發(fā)的包,可以方便的實現(xiàn)json對象與JavaBean對象互相的轉(zhuǎn)換。

pom依賴:

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

fastjson三個主要的類:

  • JSONObject代表json對象
    • JSONObject實現(xiàn)了Map接口
    • JSONObject對應(yīng)json對象。通過各種形式的get()方法獲取json對象的數(shù)據(jù),也可以用諸如size(),isEmpty()等方法獲取“鍵:值”對的個數(shù)和判空
  • JSONArray代表json對象數(shù)組
    • 內(nèi)部是由List接口中的方法來完成操作的。
  • JSON代表JSONObject和JSONArray的轉(zhuǎn)化
    • JSON類源碼分析與使用
@RequestMapping("/j4")
@ResponseBody
public String json4() throws JsonProcessingException {
    List<User> userList=new ArrayList<User>();
    User user1 = new User("胡巴1號", 3, "男");
    User user2 = new User("胡巴2號", 4, "男");
    User user3 = new User("胡巴3號", 5, "男");

    userList.add(user1);
    userList.add(user2);
    userList.add(user3);

    String s = JSON.toJSONString(userList);
    return s;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容