Jackson 中SimpleModule的作用

Jackson 中SimpleModule的作用

SimpleModule中的作用可以用于json数据类型的转换。例如我们想将前端传过的时间类型yyyy-mm-dd的类型转成localdataTime。我们可以利用SimpleModule做一个全局的配置,正对时间类型的数据。前端只需要给我们yyyy-mm-dd ,后端根据自定义 SimpleModule 进行转换。

public JavaTimeModule() {
        super(PackageVersion.VERSION);
        //序列化,
        this.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        this.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
        this.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
        //反序列化
        this.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        this.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
        this.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
    }

我们可以定义其的序列化和反序列化模式。我们也可以转其他的类型例如Long类型的转成string类型。

接下来我们定义两个接口测试一下看看。如下:

package com.medusa.gruul.account.controller;

import com.alibaba.fastjson.JSONObject;
import com.medusa.gruul.account.model.User;
import jdk.nashorn.internal.ir.ReturnNode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Objects;

@RestController
@RequestMapping("/jackson")
public class JacksonController {


    @GetMapping("/test")
    public User jackSonTest() {
        User user = new User();
        user.setId("1");
        user.setUserName("userName");
        user.setPassword("123456");
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        return  user;
    }

    @PostMapping("/test01")
    public void jackSonTest01(@RequestBody User user) {
        System.out.println(JSONObject.toJSON(user));
    }

}

一个是获取 user,一个是接受user。调用第一个接口测试发现:

在这里插入图片描述

时间类型的已经成功转换成为了yyyy-mm-dd的类型。第二个接口返回

在这里插入图片描述

可以看到成功的将yyyy-mm-dd类型的时间格式转换成为了我们需要的LocalDateTime类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

久★伴i

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值