c# - 在 C# 中读取和解析 Json 文件

标签 c# json parsing large-files

我花了两天时间“花时间”处理代码示例等,试图将一个非常大的 JSON 文件读入 c# 中的数组,以便以后可以将其拆分为二维数组进行处理。

我遇到的问题是我找不到任何人在做我想做的事的例子。这意味着我只是在编辑代码,希望能做到最好。

我已经设法让一些工作:

  • 读取文件遗漏标题,仅将值读取到数组中。
  • 在数组的每一行放置一定数量的值。 (所以我 以后可以将其拆分为二维数组)

这是使用下面的代码完成的,但是在向数组中输入几行后它会导致程序崩溃。这可能与文件大小有关。

// If the file extension was a jave file the following 
// load method will be use else it will move on to the 
// next else if statement
if (fileExtension == ".json") 
{
    int count = 0;
    int count2 = 0;
    int inOrOut = 0;
    int nRecords=1; 
    JsonTextReader reader = new JsonTextReader(new StreamReader(txtLoaction.Text));
    string[] rawData = new string[5];
    while (reader.Read())
    {
        if (reader.Value != null)
            if (inOrOut == 1)
            {
                if (count == 6)
                {
                    nRecords++;
                    Array.Resize(ref rawData, nRecords);
                    //textBox1.Text += "\r\n";
                    count = 0;
                }
                rawData[count2] += reader.Value + ","; //+"\r\n"
                inOrOut = 0;
                count++;
                if (count2 == 500)
                {
                    MessageBox.Show(rawData[499]);
                }
            }
            else
            {
                inOrOut = 1;
            }
    } 
}

我正在使用的 JSON 片段是:

[ 
    { "millis": "1000", 
      "stamp": "1273010254", 
      "datetime": "2010/5/4 21:57:34", 
      "light": "333", 
      "temp": "78.32", 
      "vcc": "3.54" }, 
] 

我需要这个 JSON 中的值。例如,我需要“3.54”,但我不希望它打印“vcc”。

我希望有人可以告诉我如何读取 JSON 文件并只提取我需要的数据并将其放入数组或稍后我可以使用的东西放入数组中。

最佳答案

使用Json.NET 让一切变得更简单怎么样? ?

    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("file.json"))
        {
            string json = r.ReadToEnd();
            List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
        }
    }

    public class Item
    {
        public int millis;
        public string stamp;
        public DateTime datetime;
        public string light;
        public float temp;
        public float vcc;
    }

您甚至可以在不声明 Item 类的情况下动态获取值

    dynamic array = JsonConvert.DeserializeObject(json);
    foreach(var item in array)
    {
        Console.WriteLine("{0} {1}", item.temp, item.vcc);
    }

关于c# - 在 C# 中读取和解析 Json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13297563/

相关文章:

c# - 打印 word 文档时边距超出可打印区域

c# - dll文件的说明

c# - ListBox、DataView 和 DataTable.RejectChanges()

java - 如何解决通用实例化问题?

parsing - Elasticsearch 索引 html 文件内容的正确策略

c# - system.invalidoperationexception : collection was modified; enumeration operation may not execute. 需要想法吗?

javascript - 在 JavaScript 中有效地将数组映射到字符串

c - 在 C 中推荐的 JSON 解析器?

java - Rest API post请求将Cucumber.json文件发送到Java中的Jira

algorithm - Q处理的QA算法