Home > OS >  How to deserialize a [System.Serializable] struct with a dictionary property
How to deserialize a [System.Serializable] struct with a dictionary property

Time:11-15

I have a struct that has a [System.Serializable] tag that looks something like this:

[Serializable]
public struct User 
{
    public string name;
}

I want to add an experiments property that is a Dictionary<string, string>. I can't make it another Serializable struct because it changes dynamically (on the backend) and the keys also contain -s.

However doing the following makes it so experiments is always deserialized as null. I've also tried using an IDictionary type.

[Serializable]
public struct User 
{
    public string name;
    public Dictionary<string, string> experiments;
}

I've confirmed that the server is sending down this json:

{
    "name": "Bob",
    "experiments": {
        "experiment-3532": "control"
    }
}

FWIW, this is how I'm using the struct

public IEnumerator GetUser(Action<User> callback, Action<string> errorCallback)
    {
        string url = "https://myurl.com/myurl/"; // fake endpoint

        UnityWebRequest request = UnityWebRequest.Get(url);
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Version", Application.version);

        yield return request.SendWebRequest();
        if (request.error == null)
            callback(JsonUtility.FromJson<User>(request.downloadHandler.text));
        else
            errorCallback("Uh oh! Network error");

        request.Dispose();
    }

CodePudding user response:

From what I see in FromJson docs:

Fields of the object must have types supported by the serializer. [..]Only plain classes and structures are supported

Dictionary is not supported. Check also this answer. I find myself comfortable with JSON.Net when working with JSON. It is one of the most used libraries, it could be your go to.

  • Related