0
\$\begingroup\$

I'm having difficulties serializing lists with the built in JsonUtility. I eventually figured out this just isn't possible with its limited capabilities.

As much as I'd like to use Newtonsoft, I cannot use that either because this is a mobile game, and from what I understand it doesn't work on Android or iOS.

Does anyone have any suggestions for how I can serialize my lists on mobile? I don't want to have to use hacky solutions to get these lists in and out of JSON.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Can you show us an example of the kind of list serialization you want to do that's giving JsonUtility trouble? That way we can verify that any solution we propose will correctly handle that problem case. \$\endgroup\$ – DMGregory May 1 at 12:19
1
\$\begingroup\$

To be able to serialize some data using Unity's built in serializer, you will have to contain your data in a class. You can't simply serialize a list as is.

Something like this should work. You can make some sort of generic class like here, if you only need to serialize lists containing different types of data:

using System.Collections.Generic;
using UnityEngine;

public class SerializationDemo : MonoBehaviour
{
    [SerializeField] List<string> yourList;

    void Start()
    {
        // Your list with some data
        yourList = new List<string> { "foo", "bar" };

        // Store your data into a container class, 
        // this can be serialized
        var data = new SaveData<string>(yourList);

        // Class contents to json using Unity's serializer
        var jsonText = JsonUtility.ToJson(data);

        // Save your json data here instead of logging it...
        // JSON: {"list":["foo","bar"]}
        Debug.Log("JSON: " + jsonText.ToString());
    }
}


[System.Serializable]
public class SaveData<T>
{
    public List<T> list;

    public SaveData(List<T> data)
    {
        this.list = data;
    }
}
\$\endgroup\$
1
\$\begingroup\$

The JSON.NET plugin for Unity officially supports "all Unity platforms including WebGL, except for WebPlayer, Windows 8.0 and Windows Phone 8.0."

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.