950b95322bd7a82655c174efd436731a6e47532c
[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 public class JsonHandler
17 {
18         public final 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, StandardCharsets.UTF_8);
34                                 BufferedReader bf = new BufferedReader(reader))
35                 {
36                         return fromJson(bf.lines().collect(Collectors.joining("\n")), type);
37                 }
38         }
39
40         public static <T> T fromJson(String src, Class<T> type)
41         {
42                 return parser.fromJson(src, type);
43         }
44
45         public static <T> T fromJsonTree(JsonElement src, Class<T> type)
46         {
47                 return parser.fromJson(src, type);
48         }
49
50         public static void writeJson(Object o, String path) throws IOException
51         {
52                 try (FileWriter writer = new FileWriter(path))
53                 {
54                         writer.write(toJson(o));
55                 }
56         }
57
58         public static String toJson(Object o)
59         {
60                 return parser.toJson(o);
61         }
62
63         public static JsonElement toJsonTree(Object o)
64         {
65                 return parser.toJsonTree(o);
66         }
67 }