Unity Json De/serializing nested data

1.5k views Asked by At

please help me! I'm trying to read a big chunk of data from a json file and most part of the data is a list of list! I dont know how to deserialize it!

So I found this guide, and did as him using the JsonFX http://www.raybarrera.com/2014/05/18/json-deserialization-using-unity-and-jsonfx/

it helped me deserialize all the other information I need except the list of list.

The following is an example of how the json file may look like, keep in mind I simplified it ten folds, cuz this is a huge dataset!

{
    "name": "Croissant",
    "price": 60,
    "foo": [{
            "poo": [1, 2]
        },
        {
            "poo": [3, 4]
        }
    ],
    "importantdata": [
        [
            0,
            1,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0
        ],
        [
            1,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0
        ]
    ]
}

So how can I make this into an object and reach the data I need like this myObject.importantdata[n]?

If more information is needed I'm happy to share, sorry Im new here!

2

There are 2 answers

1
jason.kaisersmith On

In such cases it is often best to use a website such as http://json2csharp.com/

Paste in your JSON, click on generate and it will give you a list of C# classes which conform to the structure of your JSON.

In this case it gives me

public class Foo
{
    public List<int> poo { get; set; }
}

public class RootObject
{
    public string name { get; set; }
    public int price { get; set; }
    public List<Foo> foo { get; set; }
    public List<List<int>> importantdata { get; set; }
}

I then personally use NewtonSofts Json.net to convert to/from JSON such as this; http://www.newtonsoft.com/json

using Newtonsoft.Json;


string json = File.ReadAllText("path\to\file.json");
RootObject myRootObject = JsonConvert.DeserializeObject<RootObject>(json);
0
David On

You can generate the POCO class using your sample data, try http://json2csharp.com/, which is an online tool. Visual Studio 2015 onward and VS code also has a similar menu item/command to accomplish this.

  • Paste your json string there
  • you will get all the POCO classes you need.

The auto-generated result for your case is:

public class Foo
{
    public List<int> poo { get; set; }
}

public class RootObject
{
    public string name { get; set; }
    public int price { get; set; }
    public List<Foo> foo { get; set; }
    public List<List<int>> importantdata { get; set; }
}

VS Code example: enter image description here

Visual Studio 2015 example: enter image description here