Unity3d Serialization. Serialize System.Guid using JsonUtility

Unity3d 5.3.0 introduced JsonUtility class which will help you with JSON serialization and deserialization. But this class has some limitation, and one of them: “You cannot serialize\deserialize System.Guid type

That’s a pity, especially if you’re using System.Guid in your DTO objects. But, there are solutions:

  • You can change a data type, for example, use System.String or System.UInt32 instead of System.Guid. But if you have a lot of code which uses your DTO objects it might be painful to refactor all of it.
  • The second option is to create a wrapper type with an implicit conversion to and from System.Guid. So you do not need to change any code outside of your DTO.

Here is wrapper struct which has small GC allocation footprint (around 500B per conversion):

Here is resulting JSON string:

Now you can replace Guid with SerializedGuid in DTO object:

But because of the implicit operators you do not need to change any other code:

Leave a Reply

Your email address will not be published. Required fields are marked *