Pins now have names
[Mograsim.git] / net.mograsim.logic.ui / src / net / mograsim / logic / ui / util / JsonHandler.java
1 package net.mograsim.logic.ui.util;
2
3 import java.io.BufferedReader;
4 import java.io.FileReader;
5 import java.io.FileWriter;
6 import java.io.IOException;
7
8 import com.google.gson.Gson;
9 import com.google.gson.GsonBuilder;
10
11 public class JsonHandler
12 {
13         private static Gson parser = new GsonBuilder().setPrettyPrinting().create();
14
15         @SuppressWarnings("resource")
16         public static <T> T readJson(String path, Class<T> type) throws IOException
17         {
18                 FileReader reader = new FileReader(path);
19                 BufferedReader bf = new BufferedReader(reader);
20                 bf.readLine(); // Skip version
21                 String json = bf.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').reduce("", (x, y) -> x.concat(y));
22                 T params = parser.fromJson(json, type);
23                 reader.close();
24                 return params;
25         }
26
27         public static void writeJson(Object o, String path) throws IOException
28         {
29                 @SuppressWarnings("resource")
30                 FileWriter writer = new FileWriter(path);
31                 writer.write(String.format("mograsim version: %s\n", Version.current.toString()));
32                 writer.write(parser.toJson(o));
33                 writer.close(); // TODO: Insure that writer is closed
34         }
35 }