1 package net.mograsim.logic.model.util;
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;
12 import com.google.gson.Gson;
13 import com.google.gson.GsonBuilder;
14 import com.google.gson.JsonElement;
16 import net.mograsim.logic.core.types.BitVector;
18 public class JsonHandler
20 public final static Gson parser = new GsonBuilder().registerTypeAdapter(BitVector.class, new BitVectorAdapter()).setPrettyPrinting()
23 public static <T> T readJson(String path, Class<T> type) throws IOException
25 try (FileInputStream jsonStream = new FileInputStream(path))
27 return readJson(jsonStream, type);
32 * @param input The Stream is closed after being read
34 public static <T> T readJson(InputStream input, Class<T> type) throws IOException
36 try (InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
37 BufferedReader bf = new BufferedReader(reader))
39 return fromJson(bf.lines().collect(Collectors.joining("\n")), type);
43 public static <T> T fromJson(String src, Class<T> type)
45 return parser.fromJson(src, type);
48 public static <T> T fromJsonTree(JsonElement src, Class<T> type)
50 return parser.fromJson(src, type);
53 public static void writeJson(Object o, String path) throws IOException
55 try (FileWriter writer = new FileWriter(path))
57 writer.write(toJson(o));
61 public static String toJson(Object o)
63 return parser.toJson(o);
66 public static JsonElement toJsonTree(Object o)
68 return parser.toJsonTree(o);