【WEEK3】 【DAY2】JSON Interaction Handling Part One 【English Version】

2024.3.12 Tuesday

6. JSON Interaction Handling

6.1. What is JSON

  1. JSON (JavaScript Object Notation) is a lightweight data interchange format that is widely used nowadays.
  2. It uses a text format that is completely independent of any programming language to store and represent data.
  3. Its concise and clear hierarchical structure makes JSON an ideal language for data interchange.
  4. It is easy for humans to read and write, as well as for machines to parse and generate, and effectively enhances the efficiency of network transmission.
  5. In the JavaScript language, everything is an object. Thus, any type supported by JavaScript can be represented through JSON, such as strings, numbers, objects, arrays, etc. Let’s look at its requirements and syntax format:
    • Objects are represented as key-value pairs, with data separated by commas
    • Curly braces{} hold objects
    • Square brackets [] hold arrays
  6. JSON key-value pairs are a way to save JavaScript objects, quite similar to the way JavaScript objects are written; the key name in key/value pairs is written first and enclosed in double quotes “”, separated by a colon :, followed immediately by the value.
    For example:
{"name": "Zhengsan"}
{"age": "3"}
{"gender": "male"}

6.2. Code Testing (Converting between JSON and JavaScript Objects)

6.2.1. Create a module named springmvc-05-json and add web support

6.2.2. Create a new json-1.html in the web directory and write test content

Insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>json</title>

<!--Write a JavaScript object-->
    <script type = "text/javascript">
      // Write a JavaScript object
      var user = {
        name:"zhangsan",
        age:3,
        gender:"male"
      };
    console.log(user);  // Print information

    console.log("==========");

    // Convert a JavaScript object to a JSON object
    var json1 = JSON.stringify(user);
    console.log(json1);

    console.log("==========");

    // Convert a JSON object back to a JavaScript object
    var JS1 = JSON.parse(json1);
    console.log(JS1);  // Print information

    </script>

</head>
<body>

</body>
</html>

Explanations of some methods:
console.log()
JSON.stringify()
JSON.parse()
Insert image description here

6.3. Controller Returning JSON Data

6.3.1. Jackson is a rather good Java JSON parsing tool

There are also tools like fast JSON, etc.

6.3.3. Here we use Jackson, and to use it, we need to import its jar package

Copy the code in the red box and paste it into springmvc-05-json\pom.xml
Insert image description here

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind">
<!--         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"-->

    <parent>
        <artifactId>SpringMVC_try1</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>P14</groupId>
    <artifactId>springmvc-05-json</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

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

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

</project>

6.3.4. web.xml (Using common code)

Insert image description here

<?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. Register servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Associate by specifying the location of the SpringMVC configuration file through an initialization parameter-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- Startup sequence, the smaller the number, the earlier the startup -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--All requests are intercepted by 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>

6.3.5. springmvc-servlet.xml (Using common code)

Insert image description here

<?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">

    <!-- Automatically scan the specified package, all annotated classes below are managed by the IOC container -->
    <context:component-scan base-package="P14.controller"/>

    <!-- View Resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- Prefix -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- Suffix -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

6.3.6. Create User.java

Insert image description here

package P14.project;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

// First, add the lombok dependency to pom.xml
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String gender;
}

6.3.7. Create UserController.java

Insert image description here

package P14.controller;

import P14.project.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @RequestMapping("j1")
    @ResponseBody   // This means the return value will bypass the view resolver and return a string directly
    public String json1(){
        // Create an object
        User user = new User("Zhang San", 11, "female");
        return user.toString();
    }
}

6.3.8. Add resources, configure Tomcat

Insert image description here
Insert image description here

6.3.9. Run

http://localhost:8080/springmvc_05_json_war_exploded/j1
Insert image description here

6.3.10. Use Jackson ObjectMapper package (Modify UserController.java)

  1. Reference tutorials
    https://blog.csdn.net/winterking3/article/details/123423135
    https://www.cnblogs.com/Kerryworld/p/12470523.html
package P14.controller;

import P14.project.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @RequestMapping("j1")
    @ResponseBody   // This means the return value will bypass the view resolver and return a string directly
    public String json1() throws JsonProcessingException {
        // Use ObjectMapper from the imported jackson-databind package
        ObjectMapper mapper = new ObjectMapper();

        // Create an object
        User user = new User("Zhang San", 11, "female");

        // Convert a value to string
        String str = mapper.writeValueAsString(user);
        return str;
    }
}
  1. Run
    http://localhost:8080/springmvc_05_json_war_exploded/j1
    Insert image description here
  2. Solve the character encoding issue
  • Modify UserController.java
package P14.controller;

import P14.project.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    // Fix the character encoding issue
    @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
    @ResponseBody   // This means the return value will bypass the view resolver and return a string directly
    public String json1() throws JsonProcessingException {
        // Use ObjectMapper from the imported jackson-databind package
        ObjectMapper mapper = new ObjectMapper();

        // Create an object
        User user = new User("Zhang San", 11, "female");

        // Convert a value to string
        String str = mapper.writeValueAsString(user);
        return str;
    }
}
  • 17
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值