Gson FastJson Jackson processes Date LocalDate LocalDateTime date type JSON format string
Gson processes Date LocalDate LocalDateTime date type JSON format string
When using the Gson library to serialize and deserialize objects whose properties are
Date
,LocalDate
andLocalDateTime
,
You can use annotations to specify how dates are formatted. The Gson library supports the@SerializedName
and@JsonAdapter
annotations.
-
@SerializedName
annotation: used to specify the name of the JSON attribute. You can apply the@SerializedName
annotation to the properties of the object to specify the corresponding JSON property name. -
@JsonAdapter
annotation: used to specify a custom JsonAdapter class. You can apply the@JsonAdapter
annotation to the properties of the object and specify the corresponding JsonAdapter class to format and de-format the date.
Here is a sample code that demonstrates how to use annotations to format objects whose output properties are Date
, LocalDate
, and LocalDateTime
:
Gson handles Date type
Prepare 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 Li Haozhe * @version 1.0 * @create 2023/10/19 */ @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class Emp {<!-- --> /** * account */ private String account; /** * password */ private String password; /** * Name */ private String name; /** * Gender 1 represents male and 0 represents female */ private int gender; /** * Entry Time */ @JsonAdapter(DateAdapter.class) private Date hiredate; /** * Date of resignation */ @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 to json format string
Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "Li Haozhe", 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);
The result is as follows:
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊之, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null,) {<!-- -->"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"Li Haozhe","gender":1,"hiredate":"2023-10-19 19: 10:18"}
json format string to javabean
Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "Li Haozhe", 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);
The result is as follows:
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊之, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null) {<!-- -->"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"Li Haozhe","gender":1,"hiredate":"2023-10-19 19: 10:18"} Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=Li Haozhe, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null)
Gson annotation processing Date LocalDate LocalDateTime
Prepare 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 Li Haozhe * @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); } } }
Prepare LocalDateAdapter
package com.lihaozhe.util.json.gson; /** * @author Li Haozhe * @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); } } }
Prepare 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 Li Haozhe * @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); } } }
Prepare 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 Li Haozhe * @version 1.0 * @create 2023/10/19 */ @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class Emp {<!-- --> /** * account */ private String account; /** * password */ private String password; /** * Name */ private String name; /** * Gender 1 represents male and 0 represents female */ private int gender; /** * Entry Time */ @JsonAdapter(DateAdapter.class) private Date hiredate; /** * Date of resignation */ @JsonAdapter(DateAdapter.class) private Date turnoverDate; /** * Account registration date */ @JsonAdapter(LocalDateAdapter.class) private LocalDate createDate; /** * Account registration date and time */ @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 to json format string
Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "Li Haozhe", 1); System.out.println(emp); Gson gson = new Gson(); String json = gson.toJson(emp); System.out.println(json);
The result is as follows:
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=Li Haozhe, 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":"Li Haozhe","gender":1,"hiredate":"2023-10-19 19: 20:29","createDate":"2023-10-19","createDateTime":"2023-10-19 19:20:29"}
json format string to javabean
Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "Li Haozhe", 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);
The result is as follows:
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=Li Haozhe, 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":"Li Haozhe","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=Li Haozhe, gender=1, hiredate=Thu Oct 19 19:20:29 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19 :20:29.118)
In the above code, a DataObject
class is defined, which contains properties of type Date
, LocalDate
and LocalDateTime
.
- The
Date
type attribute uses the@SerializedName
annotation, specifying the attribute name asdate
. - The
LocalDate
type attribute uses the@JsonAdapter
annotation and specifies theLocalDateAdapter
class as the custom JsonAdapter. - Attributes of type
LocalDateTime
also use the@JsonAdapter
annotation, and specify theLocalDateTimeAdapter
class as the custom JsonAdapter.
The LocalDateAdapter
and LocalDateTimeAdapter
classes respectively inherit com.google.gson.TypeAdapter
and rewrite write()
and read()
method to implement date formatting and de-formatting.
In the write()
method, convert the date object to a string and write it to JSON using the JsonWriter
.
In the read()
method, read the JSON string and convert it into a date object.
Finally, use the Gson object to serialize the DataObject object into a JSON string and print the output.
It should be noted that when using a custom JsonAdapter class, it needs to be registered into the Gson object so that Gson can correctly use them to format and de-format dates.
FastJson handles Date LocalDate LocalDateTime date type JSON format string
When using FastJson for formatted output, you can specify the date formatting method of the attribute by using the
@JSONField
annotation.
Here is a sample code that demonstrates how to use annotations to format objects whose output properties are Date
, LocalDate
, and LocalDateTime
:
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) {<!-- --> // date object DataObject dataObject = new DataObject(new Date(), LocalDate.now(), LocalDateTime.now()); // Serialize to JSON string 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; } } }
In the above code, a DataObject
class is defined, which contains properties of type Date
, LocalDate
and LocalDateTime
.
- The
Date
type attribute uses the@JSONField
annotation and specifies the date format asyyyy-MM-dd HH:mm:ss
. - The
LocalDate
type attribute uses the@JSONField
annotation and specifies the date format asyyyy-MM-dd
. - The
LocalDateTime
type attribute uses the@JSONField
annotation and specifies the date format asyyyy-MM-dd HH:mm:ss
.
By using the @JSONField
annotation on the attribute and specifying the format
attribute to specify the date format, FastJson will format the date and output it according to the specified format.
Finally, use the JSON.toJSONString()
method to serialize the DataObject
object into a JSON string and print the output.
Jackson handles Date LocalDate LocalDateTime date type JSON format string
When using Jackson for formatted output, you can specify the date formatting method of the attribute by using the
@JsonFormat
annotation.
Here is a sample code that demonstrates how to use annotations to format objects whose output properties are Date
, LocalDate
, and LocalDateTime
:
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 {<!-- --> // date object DataObject dataObject = new DataObject(new Date(), LocalDate.now(), LocalDateTime.now()); // Create ObjectMapper object ObjectMapper objectMapper = new ObjectMapper(); // Serialize to JSON string 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; } } }
In the above code, a DataObject
class is defined, including attributes of type Date
, LocalDate
and LocalDateTime
.
- The
Date
type attribute uses the@JsonFormat
annotation, and specifies the date format asyyyy-MM-dd HH:mm:ss
and the time zone asGMT + 8
. - The
LocalDate
type attribute uses the@JsonFormat
annotation and specifies the date format asyyyy-MM-dd
. - The
LocalDateTime
type attribute uses the@JsonFormat
annotation and specifies the date format asyyyy-MM-dd HH:mm:ss
.
By using the @JsonFormat
annotation on the attribute and specifying the pattern
attribute to specify the date format, Jackson will format the date and output it according to the specified format.
Finally, use the ObjectMapper
object to serialize the DataObject
object into a JSON string and print the output.