Unity Json De/serializing nested data [duplicate]

主宰稳场 提交于 2021-02-10 14:19:16

问题


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!


回答1:


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:

Visual Studio 2015 example:




回答2:


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);


来源:https://stackoverflow.com/questions/45229260/unity-json-de-serializing-nested-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!