Java中常用解析工具jackson及fastjson的使用

一、maven安裝jackson依賴

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

二、Jackson的使用

實體類轉化JSON

把實體類轉化為JSON格式數據,返回給前端 

創建 ObjectMapper obj = new ObjectMapper(); 對象,對象的 writeValueAsString 方法 會把一個實體類(必須有get、set方法)轉化為JSON對象。

package com.lxc.springboot.controller;
 
 
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController // 這個類下邊的所有方法,都會返回json,不會返回一個視圖!
public class Json {
 
    @RequestMapping(value = "/json")
    public String json() throws Exception{
        User user = new User("呂星辰", "888", 20);
        ObjectMapper obj = new ObjectMapper();
        String jsonObject = obj.writeValueAsString(user);
        return jsonObject;
    }
    // 為測試方便,在這裡寫一個實體類
    public static class User {
        private String userName;
 
        public String getUserName() {
            return userName;
        }
 
        public void setUserName(String userName) {
            this.userName = userName;
        }
 
        public String getPassword() {
            return password;
        }
 
        public void setPassword(String password) {
            this.password = password;
        }
 
        public int getAge() {
            return age;
        }
 
        public void setAge(int age) {
            this.age = age;
        }
 
        private String password;
        private int age;
        public User(String userName, String password, int age) {
            this.userName = userName;
            this.password = password;
            this.age = age;
        }
    }
}

測試:

集合轉化JSON

前端結果是:一個數組,裡邊是一個個對象

package com.lxc.springboot.controller;
 
import com.fasterxml.jackson.databind.ObjectMapper;
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 Json {
 
    @RequestMapping(value = "/json")
    public String json() throws Exception{
        // 創建一個集合
        List<User> userList = new ArrayList<>();
        for(int i = 0; i < 3; i ++) {
            userList.add(new User("用戶名"+i, "密碼"+i, 20+i));
        }
        ObjectMapper obj = new ObjectMapper();
        String jsonObject = obj.writeValueAsString(userList);
        return jsonObject;
    }
    // 上邊有實體類,這裡省略
}

 測試:

Map轉化JSON

@RestController
public class Json {
 
    @RequestMapping(value = "/json")
    public String json() throws Exception{
        // 創建一個Map
        Map<String, Object> map = new HashMap<>();
        map.put("name", "測試名");
        map.put("age", 20);
        ObjectMapper obj = new ObjectMapper();
        String jsonObject = obj.writeValueAsString(map);
        return jsonObject;
    }
}

前端結果是:對象

new Date() 轉化JSON

@RestController
public class Json {
 
    @RequestMapping(value = "/json")
    public String json() throws Exception{
        Date date = new Date();
        ObjectMapper obj = new ObjectMapper();
        String jsonObject = obj.writeValueAsString(date);
        return jsonObject;
    }
}

前端結果是:時間戳

當然,也可以自定義時間格式

@RestController
public class Json {
 
    @RequestMapping(value = "/json")
    public String json() throws Exception{
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time = sdf.format(date); // "2021-06-27 05:19:33"
        ObjectMapper obj = new ObjectMapper();
        String jsonObject = obj.writeValueAsString(time);
        return jsonObject;
    }
}

封裝

package com.lxc.springboot.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 JavaUtils {
    /**
     *  使用下邊方法需要導入依賴包:
     * <dependency>
     *     <groupId>com.fasterxml.jackson.core</groupId>
     *     <artifactId>jackson-databind</artifactId>
     *     <version>2.12.3</version>
     * </dependency>
     *
     * @param object 集合(List)、Map(HashMap)、對象(new Date)
     * @param format 時間格式化  yyyy-MM-dd hh:mm:ss
     * @return JSON格式化的字符串
     */
    public static String getJson(Object object, String format) {
        ObjectMapper objectMapper = new ObjectMapper();
        // 不使用時間戳的方式
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        // 自定義時間格式
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        // 設置時間格式化
        objectMapper.setDateFormat(sdf);
        try {
            String jsonValue = objectMapper.writeValueAsString(object);
            return jsonValue;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getJson(Object object) {
        return getJson(object, "yyyy-MM-dd hh:mm:ss");
    }
}

三、FastJson的使用

使用maven導入依賴包

<!--下邊依賴跟aop沒關系,隻是項目中用到瞭 JSONObject,所以引入fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>

常用方法:

(1)JSON.toJSONString(obejct) – java對象轉JSON字符串

(2)JSON.parseObject(string, User.class) – JSON字符串轉java對象

使用

@RestController
public class Json {
 
    @RequestMapping(value = "/json")
    public String json() throws Exception{
        List<User> userList = new ArrayList<>();
        userList.add(new User("1", "1", 20));
        String res = JSON.toJSONString(userList);
        return res;
    }

到此這篇關於Java中常用解析工具jackson及fastjson的使用的文章就介紹到這瞭,更多相關jackson和fastjson的使用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: