Search code examples
c#jsonunity-game-enginejson.net

Cannot Serialize and Deserialize JSON in Unity


I have tried Serializing and Deserializing JSON in Unity using JsonUtility and Newtonsoft.Json. But neither of them works as expected.

  • The issue with JsonUtility is it gives empty string when converting object to JSON. When converting JSON string to custom class object, and printing class's object.value it prints empty string. Irony is that it does not give any error.

  • The issue with Newtonsoft.Json is it does not work with Android and iOS builds and builds that uses IL2CPP.

C# Code

public class AddUsers : MonoBehaviour
{
    public void ConvertToJSONSample()
    {
        UserDetails userDetails1 = new UserDetails()
        {
            Id = "0001",
            Name = "John"
        };

        string JsonString = JsonUtility.ToJson(userDetails1);
        print(JsonString); ;

        UserDetails userDetails2 = JsonUtility.FromJson<UserDetails>(JsonString);
        print("User's Name is: " + userDetails2.Name);
    }
}

[Serializable]
public class UserDetails
{
    public string Id { get; set; }
    public string Name { get; set; }
}

Output

enter image description here


Solution

  • Thanks @dbc for clarification. JsonUtility probably serializes fields not properties. In the question's case, adding { get; set; } makes it a property. Using properties enables adding additional functionalities in the code. However, to make the code work with JsonUtility remove get; and set; from the code. But you will get very limited functionality by using Unity's inbuilt JsonUtility. But it has limitations. It will not work with advanced usage. For that use fork of JamesNK/Newtonsoft.Json mentioned below it works with Unity's IL2CPP builds on Android and iOS and others.

    Another method is, use fork of JamesNK/Newtonsoft.Json from Json-for-Unity. The GitHub page contains detailed explanation of how to use, how to install, its features, etc. It works with mobile builds such as Android and iOS and other IL2CPP builds. The Package is open source and is supported by the developer, unlike JSON.Net plugin which is not updated since 2016.

    Please note that using JSON.Net is an option but it is not updated since 2016, hence might give problems in latest or upcoming versions of Unity.