ToxicGLaDOS ToxicGLaDOS - 3 months ago 24
C# Question

Is it possible to deserialize a dictionary in Unity?

With a JSON file that looks like this,

{
"dict": {"key": "value"}
}


how can I make a dictionary named "dict" that looks like this one {"key": "value"} in Unity?

Here is my class.

[Serializable]
public class MyJson
{
public Dictionary<string,string> dict;
}


I don't know why but when I try to use this class and the JsonUnility.FromJson() method it doesn't seem to change dict to that dictionary that I would expect. Instead it is just null.

EDIT: I've seen that in the Unity docs it says "dictionaries are not supported" so is there some convenient method to create the dictionary easily or will I have to piece it together myself with the data?

Here is a potential JSON. This kind of gets into another problem I was having though which is that I created the JSON with python meaning I could have different value types in my dictionary, but that won't work for C# so for now it's all just strings and I'll figure something out for that later. (Probably by making it all lists then the ones that are only strings will just have 1 element)

{
"pages": [
{
"files": "[null, null, null, null]",
"imagepath": "C:/Users/Jeff/Pictures/location_sharing.png",
"pageNum": "0",
"polygons": "[[[122, 184], [178, 180], [174, 159], [126, 158]], [[191, 157], [194, 185], [241, 183], [246, 154]], [[334, 219], [323, 236], [323, 247], [338, 259], [358, 259], [364, 236], [356, 221], [344, 215]], [[512, 221], [503, 235], [508, 256], [518, 267], [538, 260], [548, 250], [541, 228], [529, 218]]]"
},
{
"files": "[null, null, null]",
"imagepath": "C:/Users/Jeff/Pictures/node.png",
"pageNum": "1",
"polygons": "[[[189, 149], [181, 152], [188, 170], [197, 182], [196, 173], [192, 153]], [[233, 176], [258, 171], [244, 144]], [[116, 260], [143, 227], [181, 210], [225, 202], [276, 199], [305, 210], [353, 222], [360, 252], [361, 266]]]"
}

Answer

Your updated example schema does not look like it is a dictionary at all. Because each element in pages is not actual nested json but a string that looks like it could be interpeted as nested json all you need to do is have

[Serializable]
public class PageContainer
{
    Page[] pages;
}

[Serializable]
public class Page
{
    public string files;
    public string imagepath;
    public string pagenum;
    public string polygons;
}

Then do a

PageContainer pageContainer = JsonUtility.FromJson<PageContainer>(yourString);

You would then potentially need to do further

FileContainer fileContainer = JsonUtility.FromJson<FileContainer>(pageContainer.files);
PolygonContainer polygonContainer = JsonUtility.FromJson<PolygonContainer>(pageContainer.polygons);

and make the necessary classes as needed.

Comments