Serializing now serializes everything; among many other things:
[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 import com.google.gson.JsonElement;
14
15 public class JsonHandler
16 {
17         // TODO: write versions differently
18         private static Gson parser = new GsonBuilder().setPrettyPrinting().create();
19
20         public static <T> T readJson(String path, Class<T> type) throws IOException
21         {
22                 try (FileInputStream jsonStream = new FileInputStream(path))
23                 {
24                         return readJson(jsonStream, type);
25                 }
26         }
27
28         /**
29          * @param input The Stream is closed after being read
30          */
31         public static <T> T readJson(InputStream input, Class<T> type) throws IOException
32         {
33                 try (InputStreamReader reader = new InputStreamReader(input); BufferedReader bf = new BufferedReader(reader))
34                 {
35                         return fromJson(bf.lines().collect(Collectors.joining("\n")), type);
36                 }
37         }
38
39         public static <T> T fromJson(String src, Class<T> type)
40         {
41                 // TODO actually parse and compare version
42                 String rawJson = src.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').collect(Collectors.joining());
43                 return parser.fromJson(rawJson, type);
44         }
45
46         public static void writeJson(Object o, String path) throws IOException
47         {
48                 try (FileWriter writer = new FileWriter(path))
49                 {
50                         writer.write(toJson(o));
51                 }
52         }
53
54         public static String toJson(Object o)
55         {
56                 return String.format("mograsim version: %s\n%s", Version.jsonCompVersion.toString(), parser.toJson(o));
57         }
58
59         public static JsonElement toJsonTree(Object o)
60         {
61                 return parser.toJsonTree(o);
62         }
63 }