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; @RestControllerpublic 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

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

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

前端结果是:时间戳

当然,也可以自定义时间格式

@RestControllerpublic 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对象

使用

@RestControllerpublic 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的使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

怠惰是贫穷的制造厂。

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

相关文章:

你感兴趣的文章:

标签云: