MPROMEditor now calls its columns "Opcode" and "muPC"
[Mograsim.git] / plugins / 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.nio.charset.StandardCharsets;
10 import java.util.stream.Collectors;
11
12 import com.google.gson.Gson;
13 import com.google.gson.GsonBuilder;
14 import com.google.gson.JsonElement;
15
16 import net.mograsim.logic.core.types.BitVector;
17
18 public class JsonHandler
19 {
20         public final static Gson parser = new GsonBuilder().registerTypeAdapter(BitVector.class, new BitVectorAdapter()).setPrettyPrinting()
21                         .create();
22
23         public static <T> T readJson(String path, Class<T> type) throws IOException
24         {
25                 try (FileInputStream jsonStream = new FileInputStream(path))
26                 {
27                         return readJson(jsonStream, type);
28                 }
29         }
30
31         /**
32          * @param input The Stream is closed after being read
33          */
34         public static <T> T readJson(InputStream input, Class<T> type) throws IOException
35         {
36                 try (InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
37                                 BufferedReader bf = new BufferedReader(reader))
38                 {
39                         return fromJson(bf.lines().collect(Collectors.joining("\n")), type);
40                 }
41         }
42
43         public static <T> T fromJson(String src, Class<T> type)
44         {
45                 return parser.fromJson(src, type);
46         }
47
48         public static <T> T fromJson(JsonElement json, Class<T> type)
49         {
50                 return parser.fromJson(json, type);
51         }
52
53         public static <T> T fromJsonTree(JsonElement src, Class<T> type)
54         {
55                 return parser.fromJson(src, type);
56         }
57
58         public static void writeJson(Object o, String path) throws IOException
59         {
60                 try (FileWriter writer = new FileWriter(path))
61                 {
62                         writer.write(toJson(o));
63                 }
64         }
65
66         public static String toJson(Object o)
67         {
68                 return parser.toJson(o);
69         }
70
71         public static JsonElement toJsonTree(Object o)
72         {
73                 return parser.toJsonTree(o);
74         }
75 }