1

I'm trying to create a convenient serialized reference to asset objects. It serialized correctly, but deserialization fails with exception

"Error setting value to 'textAssetRef' on 'TestData'."

I've prepared a small test component for Unity to illustrate this:

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;

public class Test : MonoBehaviour
{
    public TestData testData;

    public void Awake()
    {
        try
        {
            var sData = JsonConvert.SerializeObject(testData, Formatting.Indented);
            UnityEngine.Debug.Log(sData);
            testData = JsonConvert.DeserializeObject<TestData>(sData);
            UnityEngine.Debug.Log("Done.");
        }
        catch (Exception x)
        {
            UnityEngine.Debug.LogError(x.Message);
        }
    }
}


[Serializable]
public class TestData
{
    public TextAssetRef textAssetRef;
}


[Serializable]
[JsonConverter(typeof(Serialization))]
public class TextAssetRef : ObjectRef<TextAsset>
{
    public TextAssetRef() { }
    public TextAssetRef(TextAssetRef other) : base(other) { }
    public TextAssetRef(TextAsset ta) : base(ta) { }
}


[Serializable]
public class ObjectRef<T> where T : UnityEngine.Object
{
    public T obj;

    public ObjectRef() { }
    public ObjectRef(ObjectRef<T> other) { obj = other.obj; }
    public ObjectRef(T obj) { this.obj = obj; }


    public class Serialization : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var objRef = (ObjectRef<T>)value;
            var jObject = new JObject { { "path", AssetDatabase.GetAssetPath(objRef.obj) } };
            serializer.Serialize(writer, jObject);
        }

        public override bool CanConvert(Type objectType) { return objectType == typeof(ObjectRef<T>); }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);
            var assetPath = jObject.GetValue("path").Value<string>();
            return new ObjectRef<T> { obj = AssetDatabase.LoadAssetAtPath<T>(assetPath) };
        }
    }
}

To reproduce the error just create a new project with JSON.Net asset package in Unity, create empty object in scene, put this Test component on it and press Play.

What am I to do to get it deserialized correctly?

derHugo
  • 83,094
  • 9
  • 75
  • 115
v3nz
  • 33
  • 4
  • 1
    Try this with Unity's [`JsonUtility.ToJson`](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity/36244111#36244111) and see if the problem is JSON.Net. – Programmer Feb 01 '18 at 11:21

0 Answers0