Skip to content

Commit 538d2a4

Browse files
author
saikat
committed
Code sample for BAEL-2085
1 parent 9bb3310 commit 538d2a4

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package org.baeldung.gson.entities;
2+
3+
public class User {
4+
5+
private int id;
6+
private String name;
7+
private transient String nationality;
8+
9+
public User(int id, String name, String nationality) {
10+
this.id = id;
11+
this.name = name;
12+
this.nationality = nationality;
13+
}
14+
15+
public User(int id, String name) {
16+
this(id, name, null);
17+
}
18+
19+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package org.baeldung.gson.serialization.test;
2+
3+
import java.io.FileWriter;
4+
import java.io.IOException;
5+
import java.io.Writer;
6+
import java.nio.file.Files;
7+
import java.nio.file.Paths;
8+
9+
import org.baeldung.gson.entities.User;
10+
import org.junit.Assert;
11+
import org.junit.Test;
12+
import org.junit.runner.RunWith;
13+
import org.junit.runners.Parameterized;
14+
import org.junit.runners.Parameterized.Parameter;
15+
import org.junit.runners.Parameterized.Parameters;
16+
17+
import com.google.gson.Gson;
18+
import com.google.gson.GsonBuilder;
19+
20+
@RunWith(Parameterized.class)
21+
public class JsonFileUnitTest {
22+
23+
@Parameter
24+
public Object object;
25+
26+
@Parameters
27+
public static Object[] data() {
28+
return new Object[] { 123.45, new User(1, "Tom", "American") };
29+
}
30+
31+
@Test
32+
public void givenProperData_whenStoredInFile_shouldSaveJsonSuccessfully() {
33+
String filePath = "target/output.json";
34+
try (Writer writer = new FileWriter(filePath)) {
35+
Gson gson = new GsonBuilder().setPrettyPrinting().create();
36+
gson.toJson(object, writer);
37+
Assert.assertTrue(Files.exists(Paths.get(filePath)));
38+
} catch (IOException e) {
39+
e.printStackTrace();
40+
}
41+
}
42+
43+
}

0 commit comments

Comments
 (0)