1 package net.mograsim.logic.ui.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;
10 import com.google.gson.Gson;
11 import com.google.gson.GsonBuilder;
13 public class JsonHandler
15 private static Gson parser = new GsonBuilder().setPrettyPrinting().create();
17 public static <T> T readJson(String path, Class<T> type) throws IOException
19 try (FileInputStream jsonStream = new FileInputStream(path))
21 return readJson(jsonStream, type);
26 * @param input The Stream is closed after being read
28 public static <T> T readJson(InputStream input, Class<T> type) throws IOException
30 try (InputStreamReader reader = new InputStreamReader(input); BufferedReader bf = new BufferedReader(reader))
32 String json = bf.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').reduce("", (x, y) -> x.concat(y));
33 T params = parser.fromJson(json, type);
38 public static void writeJson(Object o, String path) throws IOException
40 try (FileWriter writer = new FileWriter(path))
42 writer.write(String.format("mograsim version: %s\n", Version.jsonCompVersion.toString()));
43 writer.write(parser.toJson(o));