diff --git a/gson/src/main/java/org/baeldung/gson/entities/User.java b/gson/src/main/java/org/baeldung/gson/entities/User.java new file mode 100644 index 0000000000..b413f3300e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/User.java @@ -0,0 +1,19 @@ +package org.baeldung.gson.entities; + +public class User { + + private int id; + private String name; + private transient String nationality; + + public User(int id, String name, String nationality) { + this.id = id; + this.name = name; + this.nationality = nationality; + } + + public User(int id, String name) { + this(id, name, null); + } + +} diff --git a/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java new file mode 100644 index 0000000000..f6a8de080c --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java @@ -0,0 +1,43 @@ +package org.baeldung.gson.serialization.test; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.baeldung.gson.entities.User; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +@RunWith(Parameterized.class) +public class JsonFileUnitTest { + + @Parameter + public Object object; + + @Parameters + public static Object[] data() { + return new Object[] { 123.45, new User(1, "Tom", "American") }; + } + + @Test + public void givenProperData_whenStoredInFile_shouldSaveJsonSuccessfully() { + String filePath = "target/output.json"; + try (Writer writer = new FileWriter(filePath)) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + gson.toJson(object, writer); + Assert.assertTrue(Files.exists(Paths.get(filePath))); + } catch (IOException e) { + e.printStackTrace(); + } + } + +}