Post

Java Gson을 이용하여 String 형태의 날짜를 Date로 변경

1. yyyy-MM-dd HH:mm:ss 형태

  • Json
1
2
3
{
    "dateTime": "2023-05-24 09:30:50"
}
  • ExampleDto.java
1
2
3
4
5
6
7
8
9
10
11
12
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.sql.Timestamp;

@Getter
@Setter
@NoArgsConstructor
public class ExampleDto {
    private Timestamp dateTime;
}
  • Timestamp 변환
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.example.webclient.dto.ExampleDto;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.util.Date;

public class Example {
    public void dateExample1(String json) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ExampleDto exampleDTO = gson.fromJson(json, ExampleDto.class);
    }
}

2. 밀리세컨드 형태

  • Json
1
2
3
{
    "dateTime": "1684888240164"
}
  • ExampleDto.java
1
2
3
4
5
6
7
8
9
10
11
12
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.sql.Timestamp;

@Getter
@Setter
@NoArgsConstructor
public class ExampleDto {
    private Timestamp dateTime;
}
  • Timestamp 변환
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import com.example.webclient.dto.ExampleDto;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.util.Date;

public class Example {
    final Gson builder = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
            return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
        }
    }).create();

    public void dateExample2(String json) {
        ExampleDto exampleDto = builder.fromJson(json, ExampleDto.class);
    }
}

[출처 및 참고]

This post is licensed under CC BY 4.0 by the author.