jackson 使用

Jackson、fastjson 都是json解析工具。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中使用Jackson库可以方便地进行JSON的序列化和反序列化操作。以下是使用Jackson的一些基本用法: 1. 添加Jackson依赖:在你的项目中,需要添加Jackson的依赖项。在`pom.xml`文件中,添加以下依赖项: ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency> ``` 2. 序列化对象为JSON:使用`ObjectMapper`类可以将Java对象序列化为JSON字符串。例如,假设有一个名为`User`的Java类: ```java public class User { private String name; private int age; // 省略构造函数、getter和setter方法 @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ``` 你可以使用以下代码将`User`对象序列化为JSON字符串: ```java import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { User user = new User("John Doe", 30); ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(user); System.out.println(json); } } ``` 3. 反序列化JSON为对象:使用`ObjectMapper`类可以将JSON字符串反序列化为Java对象。例如,假设有一个名为`User`的Java类: ```java public class User { private String name; private int age; // 省略构造函数、getter和setter方法 @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ``` 你可以使用以下代码将JSON字符串反序列化为`User`对象: ```java import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { String json = "{\"name\":\"John Doe\",\"age\":30}"; ObjectMapper objectMapper = new ObjectMapper(); User user = objectMapper.readValue(json, User.class); System.out.println(user); } } ``` 以上是使用Jackson库进行基本的JSON序列化和反序列化操作的示例。你可以根据需要使用更多的Jackson功能,例如处理日期、自定义序列化器等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值