dc8ace3d03a649213124678a2180e6afdb43d93b
[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         public static <T> T readJson(String path, Class<T> type) throws IOException
16         {
17                 try (FileReader reader = new FileReader(path); BufferedReader bf = new BufferedReader(reader))
18                 {
19                         String json = bf.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').reduce("", (x, y) -> x.concat(y));
20                         T params = parser.fromJson(json, type);
21                         return params;
22                 }
23         }
24
25         public static void writeJson(Object o, String path) throws IOException
26         {
27                 try (FileWriter writer = new FileWriter(path))
28                 {
29                         writer.write(String.format("mograsim version: %s\n", Version.jsonCompVersion.toString()));
30                         writer.write(parser.toJson(o));
31                 }
32         }
33 }