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

2024.3.14 Thursday

Following the previous article 【WEEK3】 【DAY3】JSON Interaction Handling Part Two【English Version】

6.7. Writing Abstract Classes

6.7.1. Reason

If the above functions are frequently used, it can be cumbersome to write them each time, so we can encapsulate these codes into a utility class.

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;
    }
}

6.7.3. Add a method json6 in UserController to verify the abstract class can be called

    @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
    }

6.7.4. Add a method json7 in UserController to verify the 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 result obtained by running method json7 is exactly the same as method json2.

6.8. FastJson

6.8.1. Overview

6.8.1.1 Introduction to fastjson.jar

fastjson.jar is a package developed by Alibaba specifically for Java development, which can conveniently implement the conversion between JSON objects and JavaBean objects, the conversion between JavaBean objects and JSON strings, and the conversion between JSON objects and JSON strings. There are many methods to implement JSON conversion, and the final results are all the same.

6.8.1.2. Three main classes of Fastjson

1. JSONObject represents a JSON object
  • JSONObject implements the Map interface, suggesting that JSONObject’s underlying operations are implemented by Map.
  • JSONObject corresponds to a JSON object, through various forms of get() methods you can get data from a JSON object, and also use methods such as size(), isEmpty() to get the number of “key-value” pairs and determine whether it is empty.
2. JSONArray represents a JSON object array
  • Internally it uses methods from the List interface to complete operations.
3. JSON represents the conversion between JSONObject and JSONArray
  • Analysis and usage of JSON class source code.
  • Carefully observing these methods, the main purpose is to implement the conversion between JSON objects, JSON object arrays, 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;
    }

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;
    }
}

6.8.4. Tips

  • For such utility classes, it is enough for us to know how to use them. When using them, we should look for the corresponding implementation based on the specific business needs, just like the commons-io toolkit we used before; just use it!
  • JSON is very important in data transmission; it is essential to learn how to use it.
  • 17
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值