Merge remote-tracking branch 'origin/development' into development
[Mograsim.git] / net.mograsim.logic.model / src / net / mograsim / logic / model / util / JsonHandler.java
1 package net.mograsim.logic.model.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 import java.util.stream.Collectors;
10
11 import com.google.gson.Gson;
12 import com.google.gson.GsonBuilder;
13
14 public class JsonHandler
15 {
16         // TODO: write versions differently
17         private static Gson parser = new GsonBuilder().setPrettyPrinting().create();
18
19         public static <T> T readJson(String path, Class<T> type) throws IOException
20         {
21                 try (FileInputStream jsonStream = new FileInputStream(path))
22                 {
23                         return readJson(jsonStream, type);
24                 }
25         }
26
27         /**
28          * @param input The Stream is closed after being read
29          */
30         public static <T> T readJson(InputStream input, Class<T> type) throws IOException
31         {
32                 try (InputStreamReader reader = new InputStreamReader(input); BufferedReader bf = new BufferedReader(reader))
33                 {
34                         return fromJson(bf.lines().collect(Collectors.joining("\n")), type);
35                 }
36         }
37
38         public static <T> T fromJson(String src, Class<T> type)
39         {
40                 // TODO actually parse and compare version
41                 String rawJson = src.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').collect(Collectors.joining());
42                 return parser.fromJson(rawJson, type);
43         }
44
45         public static void writeJson(Object o, String path) throws IOException
46         {
47                 try (FileWriter writer = new FileWriter(path))
48                 {
49                         writer.write(toJson(o));
50                 }
51         }
52
53         public static String toJson(Object o)
54         {
55                 return String.format("mograsim version: %s\n%s", Version.jsonCompVersion.toString(), parser.toJson(o));
56         }
57 }