2017-07-21 22 views
0

请帮帮我!我试图从JSON文件中读取数据的一大块和数据的大部分是列表的列表!我不知道如何反序列化它!统一的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]的数据?

如果需要更多的信息,我很高兴与大家分享,对不起林新在这里!

+0

你JSON是无效的。验证此:https://jsonformatter.curiousconcept.com/ – Azeem

回答

1

在这种情况下,它往往是最好用的网站,如您的JSON http://json2csharp.com/

粘贴,点击生成,它会给你这符合你的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

感谢队友!我最初考虑使用get和set方法,但unitydoc是jsonutility(我使用)犯规支持它,所以我不得不去适应阅读,但是这真的帮了我很多,现在我终于可以达到什么我打算达到! newtonsoft挽救了我的生活 –

0

您可以使用您的样本数据,尝试http://json2csharp.com/,这是一个在线工具生成的POCO类。 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代码示例: enter image description here

的Visual Studio 2015年例如: enter image description here