This PR is related to BAEL-6315 (#15337)

* This commit is related to BAEL-6315

This commit aims to add two classes Contact and Person.

* This commit is related to BAEL-6315

This commit aims to add a test class DeserializationUnitTest.
This commit is contained in:
Mo Helmy 2023-12-01 03:02:46 +02:00 committed by GitHub
parent d7bb6bc0a7
commit 671957da9b
3 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,5 @@
package com.baeldung.deserialization;
public record Contact(String email, String phone) {
// Constructor, getters, and other methods are automatically generated
}

View File

@ -0,0 +1,5 @@
package com.baeldung.deserialization;
public record Person(String name, int age, String address, Contact contact) {
// Constructor, getters, and other methods are automatically generated
}

View File

@ -0,0 +1,39 @@
package com.baeldung.deserialization;
import com.google.gson.Gson;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class DeserializationUnitTest {
@Test
public void givenJsonString_whenDeserialized_thenPersonRecordCreated() {
String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\"}";
Person person = new Gson().fromJson(json, Person.class);
assertEquals("John Doe", person.name());
assertEquals(30, person.age());
assertEquals("123 Main St", person.address());
}
@Test
public void givenNestedJsonString_whenDeserialized_thenPersonRecordCreated() {
String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\",\"contact\":{\"email\":\"john.doe@example.com\",\"phone\":\"555-1234\"}}";
Person person = new Gson().fromJson(json, Person.class);
assertNotNull(person);
assertEquals("John Doe", person.name());
assertEquals(30, person.age());
assertEquals("123 Main St", person.address());
Contact contact = person.contact();
assertNotNull(contact);
assertEquals("john.doe@example.com", contact.email());
assertEquals("555-1234", contact.phone());
}
}