Skip to content

Commit 852c061

Browse files
committed
adding json writer from helpers
1 parent 3645760 commit 852c061

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

CSVWriter/JSONWriter.cs

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
using System;
2+
using System.IO;
3+
using System.Collections;
4+
using System.Collections.Generic;
5+
using UnityEngine;
6+
using SerializableTypes;
7+
using Random = System.Random;
8+
using System.Linq;
9+
using Helpers;
10+
11+
[System.Serializable]
12+
public class JSONWriter
13+
{
14+
public string fileName = null;
15+
public string dirName = null;
16+
public bool append_zero_to_filename = false;
17+
18+
[SerializeField, ReadOnly] private string filePath;
19+
private StreamWriter eventWriter;
20+
private List<string> payload = new List<string>();
21+
private bool is_active = false;
22+
23+
public bool Initialize() {
24+
string dname = $"{Application.persistentDataPath}/{Helpers.SaveSystemMethods.GetCurrentDateTime()}";
25+
if (dirName != null && dirName.Length > 0) {
26+
dname = $"{Application.persistentDataPath}/{dirName}";
27+
}
28+
Helpers.SaveSystemMethods.CheckOrCreateDirectory(dname);
29+
30+
string fname = (fileName != null && fileName.Length > 0) ? fileName : System.DateTime.Now.ToString("HH-mm-ss");
31+
filePath = (append_zero_to_filename) ? Path.Combine(dname, fname+"_0.csv") : Path.Combine(dname, fname+".csv");
32+
33+
int counter = 1;
34+
while(File.Exists(filePath)) {
35+
filePath = Path.Combine(dname, fname+$"_{counter}.csv");
36+
counter++;
37+
}
38+
39+
is_active = true;
40+
return true;
41+
}
42+
43+
public static string ConvertToJSON<T>(T data) {
44+
return JsonUtility.ToJson(data, true);
45+
}
46+
47+
public static T ConvertFromJSON<T>(string data) {
48+
return JsonUtility.FromJson<T>(data);
49+
}
50+
51+
public bool SaveJSON(string json) {
52+
if (!is_active) return false;
53+
if (filePath.EndsWith(".json")) File.WriteAllText(filePath, json);
54+
else File.WriteAllText(filePath + ".json", json);
55+
return true;
56+
}
57+
public bool SaveJSON<T>(T data) {
58+
if (!is_active) return false;
59+
string json = ConvertToJSON<T>(data);
60+
if (filePath.EndsWith(".json")) File.WriteAllText(filePath, json);
61+
else File.WriteAllText(filePath + ".json", json);
62+
return true;
63+
}
64+
65+
public bool LoadJSON<T>(out T output) {
66+
if (!is_active) {
67+
output = default(T);
68+
return false;
69+
}
70+
string actualFilePath = (filePath.EndsWith(".json")) ? filePath : filePath+".json";
71+
if (Helpers.SaveSystemMethods.CheckFileExists(actualFilePath)) {
72+
string fileContents = File.ReadAllText(actualFilePath);
73+
output = ConvertFromJSON<T>(fileContents);
74+
return true;
75+
} else {
76+
output = default(T);
77+
return false;
78+
}
79+
}
80+
81+
public void Disable() {
82+
is_active = false;
83+
}
84+
}

0 commit comments

Comments
 (0)