-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonSerializer.cs
46 lines (42 loc) · 1.5 KB
/
JsonSerializer.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
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using UnityEngine;
using Object = UnityEngine.Object;
namespace QuickEye.ImportableAssets
{
/// <summary>
/// Handles serialization of types unsupported by Unity. Unity Objects are serialized like in <see cref="UnityEngine.JsonUtility"/>
/// </summary>
public class JsonSerializer : TextSerializer
{
public JsonSerializerSettings Settings { get; set; } = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new RuntimeUnityObjectConverter()
},
ContractResolver = new UnityObjectContractResolver()
};
public override Object FromText(string text, Type objectType)
{
var objectToOverwrite = ScriptableObject.CreateInstance(objectType);
JsonConvert.PopulateObject(text, objectToOverwrite, Settings);
return objectToOverwrite;
}
public override string ToText(Object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.Indented, Settings);
}
private static void HandleError(object sender, ErrorEventArgs e)
{
var ex = e.ErrorContext.Error;
if (ex is JsonSerializationException && ex.Message.Contains("Cannot deserialize the current "))
{
Debug.Log($"{ex}");
e.ErrorContext.Handled = true;
}
}
}
}