JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.76k stars 3.25k forks source link

Unity cyclic references of Unity objects #2962

Closed Draco18s closed 3 months ago

Draco18s commented 3 months ago

Newtonsoft's serializer--the one shipped via the Unity package manager--cannot serialize Unity structs without manual JsonConverters being written for every single one of them.

Usually I only have to deal with things like Vector3 which fail to deserialize because magnitude is read only.

But get a load of this gem:

JsonSerializationException: Self referencing loop detected for property 'linear' with type 'UnityEngine.Color'. Path 'MainPlayer.Faction.Color.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear.linear'.

        public static void TrySave()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
            Color c = new Color(1,0,0);
            string json = JsonConvert.SerializeObject(c, settings);
            Debug.Log(json);
        }

And of course this only generates JsonSerializationException: Self referencing loop detected for property 'linear' with type 'UnityEngine.Color'. Path ''. With an empty path. Thanks Unity.

In theory I can set settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;, which will serialize the color standalone, but the larger project ends up crashing so hard there's no crash reporter (that is: I need the cyclic references to error so I can fix them).

Epicguru commented 3 months ago

This is an issue on Unity's end, not with this library. Unity should be providing serializers for their types as part of the official package, but they don't for whatever baffling reason. You should use this: https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters

Draco18s commented 3 months ago

Hey thanks. I had no idea that package existed. Gave it a try and yeah, it works for my purposes. I have no idea why what it does differently worked for my situation, but it does.