温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

maven安装jackson依赖的示例分析

发布时间:2021-06-28 14:27:26 来源:亿速云 阅读:6355 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关maven安装jackson依赖的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

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

测试:

maven安装jackson依赖的示例分析

集合转化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;
    }
    // 上边有实体类,这里省略
}

 测试:

maven安装jackson依赖的示例分析

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

前端结果是:对象

maven安装jackson依赖的示例分析

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

前端结果是:时间戳

maven安装jackson依赖的示例分析

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

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

maven安装jackson依赖的示例分析

感谢各位的阅读!关于“maven安装jackson依赖的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI