JamesNK/Newtonsoft.Json

Unity cyclic references of Unity objects

Draco18s opened this issue · 2 comments

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).

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

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.