Advertisement

【WEEK3】 【DAY4】JSON Interaction Handling Part Three【English Version】

阅读量:

2024.3.14 Thursday

WEEK3

WEEK3

WEEK3

WEEK3

WEEK3

Contents

  • 6.7. 创建抽象类

  • 6.7.1. 理由

  • 6.7.2. 生成JsonUtils.java文件

  • 6.7.3. 在UserController中添加一个名为json6的方法来验证抽象类是否可调用

  • 6.7.4. 在UserController中添加一个名为json7的方法来验证抽象类是否具有可重用性

  • 6.7.5. 执行测试并验证结果

  • 6 . 8 . FastJson

  • 6 . 8 . 1 . 概览

  • 6 . 8 . 1 . 1 . fastjson.jar介绍

  • 在Fastjson框架中定义了三个主要类

  • JSONObject类表示一个JSON对象

  • JSONArray类表示一个JSON对象数组

  • JSON模块负责JSONObject与JSONArray之间的转换操作

  • 6.8.2 在pom.xml中导入依赖项

  • 6.8.3 进行代码测试

    • 6.8.3-1 修改UserController中的method json7

    • 6-8-3-2 创建一个新的FastJsonDemo.java文件

    • 6.8.4. Tips

6.7. Writing Abstract Classes

6.7.1. Reason

如果这些函数被频繁使用的话,每次都要手动编写它们可能会很繁琐;因此我们可以创建一个有用的类来封装这些代码.

6.7.2. Create JsonUtils.java

Insert image description here
复制代码
    package P14.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 {
    
    // This method overloads getJson, so there is no need to rewrite the specific code; simply return the default value.
    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();
        // Do not use time difference method
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        // Custom date format object
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        // Specify date format
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    }

Introduce a new method json6 in UserController for verifying that an abstract class is callable.

复制代码
    @RequestMapping("/j6_utils")
    public String json6(){
        Date date = new Date();
        return JsonUtils.getJson(date, "yyyy-MM-dd HH:mm:ss");
    //        HH is for 24-hour format, hh is for 12-hour format
    //        return JsonUtils.getJson(date); is also possible
    }

Introduce a method json7 within the UserController class for checking if an abstract class is reusable.

复制代码
    @RequestMapping("/j7_utils_j2")
    public String json7() throws JsonProcessingException {
    
        // Create a collection
        List<User> userList = new ArrayList<>();
        User user1 = new User("Zhang San", 11, "female");
        User user2 = new User("Li Si", 11, "male");
        User user3 = new User("Wang Wu", 11, "female");
        // Add users to the collection
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
    
        return JsonUtils.getJson(userList);
    }

6.7.5. Run

http://localhost:8080/springmvc_05_json_war_exploded//j6_utils

Insert image description here

http://localhost:8080/springmvc_05_json_war_exploded//j7_utils_j2

Insert image description here

The outcome achieved through the process of running method json7 is identical to method json2.

6.8. FastJson

6.8.1. Overview

6.8.1.1 Introduction to fastjson.jar

The fastjson.jar package was specifically developed by Alibaba for Java development purposes. It provides convenient functionality for converting between JSON data structures (objects) and JavaBean entities, as well as transforming JavaBean instances into JSON strings or vice versa. The package offers numerous approaches to achieve these conversions, yet all implementations ultimately yield equivalent outcomes.

6.8.1.2. Three main classes of Fastjson

1. JSONObject represents a JSON object
  • JSONObject is an instance of the Map interface, indicating that its underlying operations are implemented by Map.
  • JSONObject represents a JSON object instance. Through various getter methods, you can retrieve data from a JSON object. Additionally, utilizing methods like size() and isEmpty(), you can obtain the number of "key-value" pairs and determine if the object is empty.
2. JSONArray represents a JSON object array

The internal processes of this system rely upon methods from the List interface to execute operations.

3. JSON represents the conversion between JSONObject and JSONArray
  • Analysis and understanding of JSON class source code.
    • Careful observation of these methods primarily aims to achieve conversions among various data structures such as JSON objects, arrays of JSON objects, JavaBean objects, and JSON strings.

6.8.2. Import dependencies in pom.xml

Insert image description here
复制代码
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>

6.8.3. Code Testing

6.8.3.1.Modify the method json7 in UserController

Change it to use fastjson as the return value of the abstract class

复制代码
    @RequestMapping("/j7_utils_j2")
    public String json7() throws JsonProcessingException {
    
        // Create a collection
        List<User> userList = new ArrayList<>();
        User user1 = new User("Zhang San", 11, "female");
        User user2 = new User("Li Si", 11, "male");
        User user3 = new User("Wang Wu", 11, "female");
        // Add users to the collection
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
    
    //        return JsonUtils.getJson(userList);
    //        Parsing with fastjson is as follows
        String str = JSON.toJSONString(userList);
        return str;
    }

Upon starting, keep in mind to ensure that the fastjson dependency package is added to the Project Structure.

Insert image description here
  • Otherwise:
Insert image description here
Insert image description here

Upon deploying fastjson, the outcome of json7 remains identical to method json2 (as it was prior to any modifications).

6.8.3.2. Create a new FastJsonDemo.java

Insert image description here
复制代码
    package P14.controller;
    
    import P14.project.User;
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @RestController
    public class FastJsonDemo {
    @RequestMapping("/fj")
    public String fastjson(){
        // Create an object
        User user1 = new User("Zhang San", 3, "male");
        User user2 = new User("Li Si", 3, "male");
        User user3 = new User("Wang Wu", 3, "male");
        User user4 = new User("Zhao Liu", 3, "male");
        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
    
        System.out.println("*******Java Object to JSON String*******");
        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 String to Java Object*******");
        User jp_user1 = JSON.parseObject(str2, User.class);
        System.out.println("JSON.parseObject(str2,User.class)==>" + jp_user1);
    
        System.out.println("\n****** Java Object to JSON Object ******");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
        System.out.println("(JSONObject) JSON.toJSON(user2)==>" + jsonObject1.getString("name"));
    
        System.out.println("\n****** JSON Object to Java Object ******");
        User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
    
        return str1;
    }
    }
Insert image description here
Insert image description here

6.8.4. Tips

  • For such utility classes, it suffices for us to understand their usage. When applying them, we should seek out and implement solutions tailored to specific business requirements, akin to how we employed the commons-io toolkit earlier; simply apply them as needed.
  • JSON stands as an essential tool in data transmission; mastering its application is crucial.

全部评论 (0)

还没有任何评论哟~