-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonHelper.cs
94 lines (77 loc) · 1.91 KB
/
JsonHelper.cs
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
90
91
92
93
94
using System;
using System.Collections.Generic;
using UnityEngine;
public class JsonHelper
{
public static string ToJson<T>(T obj)
{
if (obj == null)
{
return "";
}
return JsonUtility.ToJson(obj);
}
public static string ToJson<T>(List<T> array)
{
if (array.Count == 0)
{
return null;
}
Wrapper<T> wrapper = new();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array)
{
if (array == null)
{
return null;
}
Wrapper<T> wrapper = new();
wrapper.ArrItem = array;
return JsonUtility.ToJson(wrapper);
}
public static T FromJson<T>(string json)
{
return JsonUtility.FromJson<T>(json);
}
public static List<T> FromJsonList<T>(string json)
{
if (string.IsNullOrEmpty(json))
{
return new List<T>();
}
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static T[] FromJsonArray<T>(string json)
{
if (string.IsNullOrEmpty(json))
{
return new T[0];
}
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.ArrItem;
}
[Serializable]
private class Wrapper<T>
{
public List<T> Items;
public T[] ArrItem;
}
}
public static class JsonHelperExtension
{
public static T CloneObjectViaJson<T>(T source)
{
return JsonHelper.FromJson<T>(JsonHelper.ToJson(source));
}
public static List<T> CloneListViaJson<T>(List<T> source)
{
return JsonHelper.FromJsonList<T>(JsonHelper.ToJson(source));
}
public static T[] CloneArrayViaJson<T>(T[] source)
{
return JsonHelper.FromJsonArray<T>(JsonHelper.ToJson(source));
}
}