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.util.stream.Collectors;
11 import com.google.gson.Gson;
12 import com.google.gson.GsonBuilder;
13 import com.google.gson.JsonElement;
15 public class JsonHandler
17 public final static Gson parser = new GsonBuilder().setPrettyPrinting().create();
19 public static <T> T readJson(String path, Class<T> type) throws IOException
21 try (FileInputStream jsonStream = new FileInputStream(path))
23 return readJson(jsonStream, type);
28 * @param input The Stream is closed after being read
30 public static <T> T readJson(InputStream input, Class<T> type) throws IOException
32 try (InputStreamReader reader = new InputStreamReader(input); BufferedReader bf = new BufferedReader(reader))
34 return fromJson(bf.lines().collect(Collectors.joining("\n")), type);
38 public static <T> T fromJson(String src, Class<T> type)
40 // throw away legacy version line
41 String rawJson = src.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').collect(Collectors.joining());
42 return parser.fromJson(rawJson, type);
45 public static <T> T fromJsonTree(JsonElement src, Class<T> type)
47 return parser.fromJson(src, type);
50 public static void writeJson(Object o, String path) throws IOException
52 try (FileWriter writer = new FileWriter(path))
54 writer.write(toJson(o));
58 public static String toJson(Object o)
60 return parser.toJson(o);
63 public static JsonElement toJsonTree(Object o)
65 return parser.toJsonTree(o);