Unity Json De /序列化嵌套数据

时间:2017-07-21 04:56:32

标签: c# json deserialization unity5 jsonfx

请帮帮我!我试图从json文件中读取大块数据,大部分数据都是列表清单!我不知道如何反序列化它!

所以我找到了这个指南,并使用JsonFX做了他 http://www.raybarrera.com/2014/05/18/json-deserialization-using-unity-and-jsonfx/

它帮助我反序列化除了列表列表之外我需要的所有其他信息。

以下是json文件的外观示例,请记住我将其简化了十倍,因为这是一个庞大的数据集!

{
    "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
        ]
    ]
}

那么我怎样才能将它变成一个对象并获得我需要的数据myObject.importantdata[n]

如果需要更多信息,我很乐意分享,抱歉我是新来的!

2 个答案:

答案 0 :(得分:1)

在这种情况下,通常最好使用http://json2csharp.com/

等网站

粘贴到JSON中,单击generate,它将为您提供符合JSON结构的C#类列表。

在这种情况下,它给了我

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

然后我个人使用NewtonSofts Json.net转换为JSON,如此转换; http://www.newtonsoft.com/json

using Newtonsoft.Json;


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

答案 1 :(得分:0)

您可以使用示例数据生成POCO类,尝试使用http://json2csharp.com/这是一个在线工具。 Visual Studio 2015以及VS代码也有类似的菜单项/命令来完成此任务。

  • 将json字符串粘贴到那里
  • 您将获得所需的所有POCO课程。

您的案例的自动生成结果是:

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示例: enter image description here

Visual Studio 2015示例: enter image description here

相关问题