1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】APIのレスポンスで日付型のJSONに"T"が含まれてしまう

Last updated at Posted at 2019-07-30

JavaでWeb APIを作ったとき、レスポンスにおいてLocalDateTime型などの日付型が

2019-01-01T01:00:00

のようになってしまう場合の解決方法

解決方法

  • シリアライズのアダプタを作成
  • レスポンスのモデルがあるパッケージにpackage-info.javaを作成し、作成したアダプタを読み込む

JAXBでの例

アダプタを作成

LocalDateAdapter.java
package api.adapters;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class LocalDateAdapter extends XmlAdapter<String, LocalDate> {
	@Override
	public LocalDate unmarshal(String s) throws Exception {

		if (s == null) {
			return null;
		}
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDate dateTime = LocalDate.parse(s, formatter);
		return dateTime;
	}

	@Override
	public String marshal(LocalDate d) throws Exception {
		if (d == null) {
			return null;
		}
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String formattedDateTime = d.format(formatter);
		return formattedDateTime;
	}
}
LocalDateTimeAdapter.java
package api.adapters;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
	@Override
	public LocalDateTime unmarshal(String s) throws Exception {

		if (s == null) {
			return null;
		}
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime dateTime = LocalDateTime.parse(s, formatter);
		return dateTime;
	}

	@Override
	public String marshal(LocalDateTime d) throws Exception {
		if (d == null) {
			return null;
		}
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String formattedDateTime = d.format(formatter);
		return formattedDateTime;
	}
}

package-infoで読み込む

package-info.java
//アダプタをアノテーションで付与
@XmlJavaTypeAdapters(value = { @XmlJavaTypeAdapter(value = LocalDateTimeAdapter.class, type = java.time.LocalDateTime.class),
@XmlJavaTypeAdapter(value = LocalDateAdapter.class, type = java.time.LocalDate.class) })
package api.model.response;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;

// アダプタをインポート
import api.adapters.LocalDateAdapter;
import api.adapters.LocalDateTimeAdapter;
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?