Gson FastJson Jackson 出来 Date LocalDate LocalDateTime 日期类型JSON格式字符串

61 篇文章 2 订阅
43 篇文章 2 订阅

Gson FastJson Jackson 处理 Date LocalDate LocalDateTime 日期类型JSON格式字符串

Gson 处理 Date LocalDate LocalDateTime 日期类型JSON格式字符串

要在使用Gson库进行属性为DateLocalDateLocalDateTime的对象的序列化和反序列化时,
可以使用注解来指定日期的格式化方式。Gson库支持@SerializedName@JsonAdapter注解。

  1. @SerializedName注解:用于指定JSON属性的名称。可以将@SerializedName注解应用在对象的属性上,指定对应的JSON属性名称。

  2. @JsonAdapter注解:用于指定自定义的JsonAdapter类。可以将@JsonAdapter注解应用在对象的属性上,指定对应的JsonAdapter类来进行日期的格式化和反格式化。

下面是一个示例代码,演示如何使用注解来格式化输出属性为DateLocalDateLocalDateTime的对象:

Gson 处理 Date 类型

准备javabean

package com.lihaozhe.json.gson;

import com.google.gson.annotations.JsonAdapter;
import com.lihaozhe.util.date.DateUtils;
import com.lihaozhe.util.json.gson.DateAdapter;
import com.lihaozhe.util.json.gson.LocalDateAdapter;
import com.lihaozhe.util.json.gson.LocalDateTimeAdapter;
import lombok.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    /**
     * 账号
     */
    private String account;
    /**
     * 密码
     */
    private String password;
    /**
     * 姓名
     */
    private String name;
    /**
     * 性别 1 代表男性 0 代表女性
     */
    private int gender;
    /**
     * 入职时间
     */
    @JsonAdapter(DateAdapter.class)
    private Date hiredate;
    /**
     * 离职日期
     */
    @JsonAdapter(DateAdapter.class)
    private Date turnoverDate;
    
    public Emp(String account, String password, String name, int gender) {
        this.account = account;
        this.password = password;
        this.name = name;
        this.gender = gender;
        this.hiredate = new Date();
    }

}

javabean转json格式字符串

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String json = gson.toJson(emp);
System.out.println(json);

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null,)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:10:18"}

json格式字符串转javabean

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String json = gson.toJson(emp);
System.out.println(json);
Emp fromJson = gson.fromJson(json, Emp.class);
System.out.println(fromJson);
        

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:10:18"}
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null)

Gson 注解方式处理 Date LocalDate LocalDateTime

准备 DateAdapter

package com.lihaozhe.util.json.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
public class DateAdapter implements JsonDeserializer<Date>, JsonSerializer<Date> {
    private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(dateFormat.format(src));
    }

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            return dateFormat.parse(json.getAsString());
        } catch (Exception e) {
            throw new JsonParseException(e);
        }
    }
}

准备 LocalDateAdapter

package com.lihaozhe.util.json.gson;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateAdapter implements JsonDeserializer<LocalDate>, JsonSerializer<LocalDate> {
    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(dateTimeFormatter.format(src));
    }

    @Override
    public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            return LocalDate.parse(json.getAsString(), dateTimeFormatter);
        } catch (Exception e) {
            throw new JsonParseException(e);
        }
    }
}

准备 LocalDateTimeAdapter

package com.lihaozhe.util.json.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
public class LocalDateTimeAdapter implements JsonDeserializer<LocalDateTime>, JsonSerializer<LocalDateTime> {
    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(dateTimeFormatter.format(src));
    }

    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            return LocalDateTime.parse(json.getAsString(), dateTimeFormatter);
        } catch (Exception e) {
            throw new JsonParseException(e);
        }
    }
}

准备javabean

package com.lihaozhe.json.gson;

import com.google.gson.annotations.JsonAdapter;
import com.lihaozhe.util.date.DateUtils;
import com.lihaozhe.util.json.gson.DateAdapter;
import com.lihaozhe.util.json.gson.LocalDateAdapter;
import com.lihaozhe.util.json.gson.LocalDateTimeAdapter;
import lombok.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    /**
     * 账号
     */
    private String account;
    /**
     * 密码
     */
    private String password;
    /**
     * 姓名
     */
    private String name;
    /**
     * 性别 1 代表男性 0 代表女性
     */
    private int gender;

    /**
     * 入职时间
     */
    @JsonAdapter(DateAdapter.class)
    private Date hiredate;
    /**
     * 离职日期
     */
    @JsonAdapter(DateAdapter.class)
    private Date turnoverDate;
    /**
     * 账号注册日期
     */
    @JsonAdapter(LocalDateAdapter.class)
    private LocalDate createDate;
    /**
     * 账号注册日期时间
     */
    @JsonAdapter(LocalDateTimeAdapter.class)
    private LocalDateTime createDateTime;

    public Emp(String account, String password, String name, int gender) {
        this.account = account;
        this.password = password;
        this.name = name;
        this.gender = gender;
        this.hiredate = new Date();
        this.createDate = LocalDate.now();
        this.createDateTime = LocalDateTime.now();
    }
}

javabean转json格式字符串

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new Gson();
String json = gson.toJson(emp);
System.out.println(json);

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:20:29 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:20:29.118)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:20:29","createDate":"2023-10-19","createDateTime":"2023-10-19 19:20:29"}

json格式字符串转javabean

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new Gson();
String json = gson.toJson(emp);
System.out.println(json);
Emp fromJson = gson.fromJson(json, Emp.class);
System.out.println(fromJson);
        

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:20:29 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:20:29.118)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:20:29","createDate":"2023-10-19","createDateTime":"2023-10-19 19:20:29"}
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:20:29 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:20:29.118)

在上述代码中,定义了一个DataObject类,包含了DateLocalDateLocalDateTime类型的属性。

  • Date类型的属性使用了@SerializedName注解,将属性名称指定为date
  • LocalDate类型的属性使用了@JsonAdapter注解,并指定了LocalDateAdapter类作为自定义的JsonAdapter。
  • LocalDateTime类型的属性也使用了@JsonAdapter注解,并指定了LocalDateTimeAdapter类作为自定义的JsonAdapter。

LocalDateAdapterLocalDateTimeAdapter类分别继承了com.google.gson.TypeAdapter,并重写了write()read()方法来实现日期的格式化和反格式化。

write()方法中,将日期对象转换为字符串,并使用JsonWriter写入JSON。

read()方法中,读取JSON字符串,并将其转换为日期对象。

最后,使用Gson对象将DataObject对象序列化为JSON字符串,并打印输出。

需要注意的是,当使用自定义的JsonAdapter类时,需要将其注册到Gson对象中,以便Gson能够正确地使用它们进行日期的格式化和反格式化。

FastJson 处理 Date LocalDate LocalDateTime 日期类型JSON格式字符串

在使用FastJson进行格式化输出时,可以通过使用@JSONField注解来指定属性的日期格式化方式。

下面是一个示例代码,演示如何使用注解来格式化输出属性为DateLocalDateLocalDateTime的对象:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        // 日期对象
        DataObject dataObject = new DataObject(new Date(), LocalDate.now(), LocalDateTime.now());

        // 序列化为JSON字符串
        String json = JSON.toJSONString(dataObject);

        System.out.println("JSON: " + json);
    }

    static class DataObject {
        @JSONField(format = "yyyy-MM-dd HH:mm:ss")
        private Date date;

        @JSONField(format = "yyyy-MM-dd")
        private LocalDate localDate;

        @JSONField(format = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime localDateTime;

        public DataObject(Date date, LocalDate localDate, LocalDateTime localDateTime) {
            this.date = date;
            this.localDate = localDate;
            this.localDateTime = localDateTime;
        }
    }
}

在上述代码中,定义了一个DataObject类,包含了DateLocalDateLocalDateTime类型的属性。

  • Date类型的属性使用了@JSONField注解,并指定了日期格式为yyyy-MM-dd HH:mm:ss
  • LocalDate类型的属性使用了@JSONField注解,并指定了日期格式为yyyy-MM-dd
  • LocalDateTime类型的属性使用了@JSONField注解,并指定了日期格式为yyyy-MM-dd HH:mm:ss

通过在属性上使用@JSONField注解,并指定format属性来指定日期格式,FastJson会根据指定的格式对日期进行格式化输出。

最后,使用JSON.toJSONString()方法将DataObject对象序列化为JSON字符串,并打印输出。

Jackson 处理 Date LocalDate LocalDateTime 日期类型JSON格式字符串

在使用Jackson进行格式化输出时,可以通过使用@JsonFormat注解来指定属性的日期格式化方式。

下面是一个示例代码,演示如何使用注解来格式化输出属性为DateLocalDateLocalDateTime的对象:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws IOException {
        // 日期对象
        DataObject dataObject = new DataObject(new Date(), LocalDate.now(), LocalDateTime.now());

        // 创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 序列化为JSON字符串
        String json = objectMapper.writeValueAsString(dataObject);

        System.out.println("JSON: " + json);
    }

    static class DataObject {
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH-mm-ss", locale = "zh", timezone = "GMT+8")
    	@JsonSerialize(using = DateSerializer.class)
    	@JsonDeserialize(using = DateDeserializers.DateDeserializer.class)
        private Date date;

        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", locale = "zh", timezone = "GMT+8")
    	@JsonSerialize(using = LocalDateSerializer.class)
    	@JsonDeserialize(using = LocalDateDeserializer.class)
        private LocalDate localDate;

       @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH-mm-ss", locale = "zh", timezone = "GMT+8")
    	@JsonSerialize(using = DateSerializer.class)
    	@JsonDeserialize(using = DateDeserializers.DateDeserializer.class)
        private LocalDateTime localDateTime;

        public DataObject(Date date, LocalDate localDate, LocalDateTime localDateTime) {
            this.date = date;
            this.localDate = localDate;
            this.localDateTime = localDateTime;
        }
    }
}

在上述代码中,定义了一个DataObject类,包含了DateLocalDateLocalDateTime类型的属性。

  • Date类型的属性使用了@JsonFormat注解,并指定了日期格式为yyyy-MM-dd HH:mm:ss,时区为GMT+8
  • LocalDate类型的属性使用了@JsonFormat注解,并指定了日期格式为yyyy-MM-dd
  • LocalDateTime类型的属性使用了@JsonFormat注解,并指定了日期格式为yyyy-MM-dd HH:mm:ss

通过在属性上使用@JsonFormat注解,并指定pattern属性来指定日期格式,Jackson会根据指定的格式对日期进行格式化输出。

最后,使用ObjectMapper对象将DataObject对象序列化为JSON字符串,并打印输出。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

李昊哲小课

桃李不言下自成蹊

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

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

打赏作者

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

抵扣说明:

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

余额充值