mapping.json is now loaded by the class loader
[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.FileInputStream;
5 import java.io.FileWriter;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9
10 import com.google.gson.Gson;
11 import com.google.gson.GsonBuilder;
12
13 public class JsonHandler
14 {
15         private static Gson parser = new GsonBuilder().setPrettyPrinting().create();
16
17         public static <T> T readJson(String path, Class<T> type) throws IOException
18         {
19                 try (FileInputStream jsonStream = new FileInputStream(path))
20                 {
21                         return readJson(jsonStream, type);
22                 }
23         }
24
25         /**
26          * @param input The Stream is closed after being read
27          */
28         public static <T> T readJson(InputStream input, Class<T> type) throws IOException
29         {
30                 try (InputStreamReader reader = new InputStreamReader(input); BufferedReader bf = new BufferedReader(reader))
31                 {
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);
34                         return params;
35                 }
36         }
37
38         public static void writeJson(Object o, String path) throws IOException
39         {
40                 try (FileWriter writer = new FileWriter(path))
41                 {
42                         writer.write(String.format("mograsim version: %s\n", Version.jsonCompVersion.toString()));
43                         writer.write(parser.toJson(o));
44                 }
45         }
46 }