Last active
January 30, 2020 09:23
-
-
Save sindrijo/0054543b248dcd5f2e3642a87821d023 to your computer and use it in GitHub Desktop.
Json.Net JsonConverter for Unity3D types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Converters; | |
using Newtonsoft.Json.Linq; | |
using UnityEngine; | |
internal static class UnityTypeSupport | |
{ | |
#if UNITY_EDITOR | |
[UnityEditor.InitializeOnLoadMethod] | |
#else | |
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)] | |
#endif | |
private static void Init() | |
{ | |
JsonConvert.DefaultSettings += GetJsonSerializerSettings; | |
} | |
private static JsonSerializerSettings GetJsonSerializerSettings() | |
{ | |
var settings = new JsonSerializerSettings(); | |
settings.Converters.Add(new UnityTypeConverter()); | |
settings.Converters.Add(new ScriptableObjectCreator()); | |
return settings; | |
} | |
private class UnityTypeConverter : JsonConverter | |
{ | |
private static readonly HashSet<Type> UnityEngineTypes; | |
static UnityTypeConverter() | |
{ | |
UnityEngineTypes = new HashSet<Type>(typeof(UnityEngine.Object).Assembly.GetTypes()); | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
writer.WriteRawValue(JsonUtility.ToJson(value)); | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
if (typeof(ScriptableObject).IsAssignableFrom(objectType)) | |
{ | |
JsonUtility.FromJsonOverwrite(JObject.Load(reader).ToString(), existingValue); | |
return existingValue; | |
} | |
return JsonUtility.FromJson(JObject.Load(reader).ToString(), objectType); | |
} | |
public override bool CanConvert(Type objectType) | |
{ | |
return IsUnityEngineType(objectType); | |
} | |
private static bool IsUnityEngineType(Type objectType) | |
{ | |
return UnityEngineTypes.Contains(objectType); | |
} | |
} | |
private class ScriptableObjectCreator : CustomCreationConverter<ScriptableObject> | |
{ | |
public override ScriptableObject Create(Type objectType) | |
{ | |
return ScriptableObject.CreateInstance(objectType); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment