1 package net.mograsim.logic.model.util;
3 import java.io.BufferedReader;
4 import java.io.FileInputStream;
5 import java.io.FileWriter;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.nio.charset.StandardCharsets;
10 import java.util.stream.Collectors;
12 import com.google.gson.Gson;
13 import com.google.gson.GsonBuilder;
14 import com.google.gson.JsonElement;
16 public class JsonHandler
18 public final static Gson parser = new GsonBuilder().setPrettyPrinting().create();
20 public static <T> T readJson(String path, Class<T> type) throws IOException
22 try (FileInputStream jsonStream = new FileInputStream(path))
24 return readJson(jsonStream, type);
29 * @param input The Stream is closed after being read
31 public static <T> T readJson(InputStream input, Class<T> type) throws IOException
33 try (InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
34 BufferedReader bf = new BufferedReader(reader))
36 return fromJson(bf.lines().collect(Collectors.joining("\n")), type);
40 public static <T> T fromJson(String src, Class<T> type)
42 // throw away legacy version line
43 String rawJson = src.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').collect(Collectors.joining());
44 return parser.fromJson(rawJson, type);
47 public static <T> T fromJsonTree(JsonElement src, Class<T> type)
49 return parser.fromJson(src, type);
52 public static void writeJson(Object o, String path) throws IOException
54 try (FileWriter writer = new FileWriter(path))
56 writer.write(toJson(o));
60 public static String toJson(Object o)
62 return parser.toJson(o);
65 public static JsonElement toJsonTree(Object o)
67 return parser.toJsonTree(o);