How to serialize and deserialize LocalDateTime type with GSON

I used GSON to serialize and deserialize the LocalDateTime type, so make a note of how to use it.

Target class

There is a member of type LocalDateTime in SampleDto.

SampleDto.java


public class SampleDto implements JsonSerializer<SampleDto>, JsonDeserializer<SampleDto> {
	private static final long serialVersionUID = 8349420239867344581L;

	private String key;
	private LocalDateTime localDateTime = LocalDateTime.now();

	public SampleDto(String key, LocalDateTime localDateTime) {
		this.key = key;
		this.localDateTime = localDateTime;
	}

	@Override
	public JsonElement serialize(SampleDto src, Type typeOfSrc, JsonSerializationContext context) {
		DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
		JsonObject result = new JsonObject();
		result.add("key", new JsonPrimitive(key));
		// LocalDateTime Serialize
		result.add("localDateTime", new JsonPrimitive(formatter.format(localDateTime)));
		return result;
	}

	@Override
	public SampleDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {
		DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
		final JsonObject jsonObject = json.getAsJsonObject();
		String key = jsonObject.get("key").getAsString();
		// LocalDateTime Deserialize
		LocalDateTime localDateTime = formatter.parse(jsonObject.get("localDateTime").getAsString(),
				LocalDateTime::from);

		return new SampleDto(key, localDateTime);
	}

	public LocalDateTime getLocalDateTime() {
		return localDateTime;
	}
}

Test class

I also created a test class as follows.

SampleDtoTest.java


ublic class SampleDtoTest {
	private static Gson gson;
	private static final GsonBuilder gsonBuilder = new GsonBuilder();
	private static SampleDto sampleDto;

	@BeforeClass
	public static void createGson() {
		gsonBuilder.registerTypeAdapter(SampleDto.class, new SampleDto("test", LocalDateTime.of(2018, 06, 11, 00, 00)));
		gson = gsonBuilder.create();
	}

	@BeforeClass
	public static void generateData() {
		sampleDto = new SampleDto("test", LocalDateTime.of(2018, 06, 11, 00, 00));
	}

	@Test
	public void testJSON() {
		String json = gson.toJson(sampleDto);
		SampleDto fromJson = gson.fromJson(json, SampleDto.class);
		assertTrue(fromJson.getLocalDateTime().equals(sampleDto.getLocalDateTime()));
	}
}

Recommended Posts

How to serialize and deserialize LocalDateTime type with GSON
How to build API with GraphQL and Rails
How to type backslash \
How to use RealSense with ubuntu 20.04 and ROS Noetic
How to install Gradle and Kotlin with SDKMAN (Mac)
Common problems with WSL and how to deal with them
How to number (number) with html.erb
How to update with activerecord-import
How to deal with different versions of rbenv and Ruby
How to scroll horizontally with ScrollView
How to use StringBurrer and Arrays.toString.
How to get started with slim
How to use EventBus3 and ThreadMode
How to enclose any character with "~"
How to call classes and methods
[Tips] How to solve problems with XCode and Swift for beginners
How to use equality and equality (how to use equals)
How to use mssql-tools with alpine
How to connect Heroku and Sequel
[Convenient to remember !!!] How to convert from LocalDate type to character string and from character string to LocalDate type
How to get along with Rails
[Java] How to convert from String to Path type and get the path
How to encrypt and decrypt with RSA public key in Java
Shape and serialize nicely with Jackson
How to start Camunda with Docker
How to use Java enum type
How to deploy to AWS using NUXTJS official S3 and CloudFront? With docker-compose
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
How to realize hybrid search using morphological analysis and Ngram with Solr
[Swift] How to connect TabBar with Storyboard Reference and also use NavigationController
How to use args :, environment :, env_file: and .env files with docker-compose command
How to create a server executable JAR and WAR with Spring gradle
[Node.js express Docker] How to define Docker environment variables and load them with node.js
[Rails] How to create a table, add a column, and change the column type
How to make an app with a plugin mechanism [C # and Java]
Java8 / 9 Beginners: Stream API addiction points and how to deal with them
How to crop an image with libGDX
How to adjustTextPosition with iOS Keyboard Extension
How to share files with Docker Toolbox
How to compile Java with VsCode & Ant
[Java] How to compare with equals method
[Android] How to deal with dark themes
How to use BootStrap with Play Framework
[Rails] How to use rails console with docker
How to switch thumbnail images with JavaScript
[Note] How to get started with Rspec
[Java] How to output and write files!
How to do API-based control with cancancan
How to set up and use kapt
How to achieve file download with Feign
How to build SquashTM and how to support Japanese
How to update related models with accepts_nested_attributes_for
How to set JAVA_HOME with Maven appassembler-maven-plugin
How to map tsrange type in Hibernate
How to implement TextInputLayout with validation function
How to find the tens and ones
How to handle sign-in errors with devise
How to delete data with foreign key
[Easy] How to upgrade Ruby and bundler
How to test private scope with JUnit
How to monitor nginx with docker-compose with datadog