-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJsonUtilityEx.cs
More file actions
89 lines (75 loc) · 3.15 KB
/
JsonUtilityEx.cs
File metadata and controls
89 lines (75 loc) · 3.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System.IO;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
namespace com.mapcolonies.core.Utilities
{
public enum FileLocation
{
StreamingAssets = 0,
PersistentData = 1
}
public static class JsonUtilityEx
{
public static async UniTask<T> FromJsonFileAsync<T>(string path)
{
string json = await FileIOUtility.ReadTextFileAsync(path);
return JsonConvert.DeserializeObject<T>(json);
}
public static async UniTask SaveJsonToFileAsync<T>(string path, T data)
{
string json = JsonConvert.SerializeObject(data, Formatting.Indented);
await FileIOUtility.WriteTextFileAsync(path, json);
}
public static async UniTask<T> LoadRemoteJsonAsync<T>(string url)
{
using UnityWebRequest request = UnityWebRequest.Get(url);
await request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
throw new IOException($"Failed to load remote JSON: {request.error}");
return JsonConvert.DeserializeObject<T>(request.downloadHandler.text);
}
public static async UniTask<T> LoadJsonAsync<T>(string relativePath, FileLocation location = FileLocation.StreamingAssets)
{
string path;
switch (location)
{
case FileLocation.PersistentData:
path = Path.Combine(Application.persistentDataPath, relativePath);
break;
case FileLocation.StreamingAssets:
path = Path.Combine(Application.streamingAssetsPath, relativePath);
break;
default:
Debug.LogWarning($"Unknown file location {location}. Using streaming assets as default.");
path = Path.Combine(Application.streamingAssetsPath, relativePath);
break;
}
return await FromJsonFileAsync<T>(path);
}
public static async UniTask SaveJsonAsync<T>(string relativePath, T data)
{
string path = Path.Combine(Application.persistentDataPath, relativePath);
await SaveJsonToFileAsync(path, data);
}
public static async UniTask<bool> DoesJsonExistAsync(string relativePath, FileLocation location = FileLocation.PersistentData)
{
string path;
switch (location)
{
case FileLocation.PersistentData:
path = Path.Combine(Application.persistentDataPath, relativePath);
break;
case FileLocation.StreamingAssets:
path = Path.Combine(Application.streamingAssetsPath, relativePath);
break;
default:
Debug.LogWarning($"Unknown file location {location}. Using persistent data as default.");
path = Path.Combine(Application.persistentDataPath, relativePath);
break;
}
return await FileIOUtility.FileExistsAsync(path);
}
}
}