当前位置: 首页 > news >正文

【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】

Contents

  • 6.7. Writing Abstract Classes
    • 6.7.1. Reason
    • 6.7.2. Create JsonUtils.java
    • 6.7.3. Add a method json6 in UserController to verify the abstract class can be called
    • 6.7.4. Add a method json7 in UserController to verify the abstract class is reusable
    • 6.7.5. Run
  • 6.8. FastJson
    • 6.8.1. Overview
      • 6.8.1.1 Introduction to fastjson.jar
      • 6.8.1.2. Three main classes of Fastjson
        • 1. JSONObject represents a JSON object
        • 2. JSONArray represents a JSON object array
        • 3. JSON represents the conversion between JSONObject and JSONArray
    • 6.8.2. Import dependencies in pom.xml
    • 6.8.3. Code Testing
      • 6.8.3.1.Modify the method json7 in UserController
      • 6.8.3.2. Create a new FastJsonDemo.java
    • 6.8.4. Tips

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 methodmapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);// Custom date format objectSimpleDateFormat sdf = new SimpleDateFormat(dateFormat);// Specify date formatmapper.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 collectionList<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 collectionuserList.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 collectionList<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 collectionuserList.add(user1);userList.add(user2);userList.add(user3);//        return JsonUtils.getJson(userList);
//        Parsing with fastjson is as followsString str = JSON.toJSONString(userList);return str;}
  • Before running, remember to add the fastjson dependency package in Project Structure
    Insert image description here
  • Otherwise:
    Insert image description here
  • Execution
    http://localhost:8080/springmvc_05_json_war_exploded/j7_utils_j2
    Insert image description here
    After using fastjson, the result of json7 is still exactly the same as method json2 (the same as before modifying json7).

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 objectUser 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;}
}
  • Run (Output a JSON string from a Java object as the page response)
    http://localhost:8080/springmvc_05_json_war_exploded/fj
    Insert image description here
    Insert image description here

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.
http://www.lryc.cn/news/320814.html

相关文章:

  • 蓝桥杯物联网竞赛_STM32L071_12_按键中断与串口中断
  • Java安全 反序列化(1) URLDNS链原理分析
  • 电脑插上网线之后仍然没网络怎么办?
  • easyexcel读和写excel
  • 路由器级联
  • CentOS7使用Docker部署.net Webapi
  • Windows程序员用MAC:初始设置(用起来像win一些)
  • 基于深度学习YOLOv8+Pyqt5的工地安全帽头盔佩戴检测识别系统(源码+跑通说明文件)
  • csv编辑器是干什么的?
  • 计算机网络——物理层(奈氏准则和香农定理)
  • XML语言的学习记录3-解析
  • 【Linux】cat vim 命令存在着什么区别?
  • MeterSphere和Jmeter使用总结
  • 学习笔记Day8:GEO数据挖掘-基因表达芯片
  • 如何将大华dav视频转mp4?一键无损清晰转换~
  • 数字化转型导师坚鹏:人工智能在金融机构数字化转型中的应用
  • 部署Zabbix Agents添加使能监测服务器_Windows平台_MSI/Archive模式
  • 十一 超级数据查看器 讲解稿 详情6 导出功能
  • java遍历文件目录去除中文文件名
  • LeetCode Python - 61. 旋转链表
  • k8s client-java创建pod常见问题
  • C++——字符串、读写文件、结构体、枚举
  • vscode 运行 java 项目之解决“Build failed, do you want to continue”的问题
  • yocto编译测试
  • rsync+inotify-tools文件传输
  • UGUI界面性能优化3-合理规划界面层级结构
  • 《论文阅读》EmpDG:多分辨率交互式移情对话生成 COLING 2020
  • C语言calloc函数的特点,效率低。但是进行初始化操作
  • 项目中遇到的sql问题记录
  • Python Web开发记录 Day13:Django part7 Ajax入门与案例(任务管理)