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

我花了两天时间“花时间”处理代码示例等,试图将一个非常大的 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);
    }

https://stackoverflow.com/questions/13297563/

相关文章:

python - JSON解码错误: Expecting value: line 1 column

jquery - 将数组传递给 $.ajax() 中的 ajax 请求

php - 如何使用 PHP 从 JSON 中提取数据?

jquery - 如何使用 jQuery/JavaScript 解析 JSON 数据?

javascript - 打印 JSON 解析的对象?

jquery - 如何在没有表单的情况下将字符串数组发布到 ASP.NET MVC Controll

ajax - 将 .ajax() 与 JSONP 一起使用的基本示例?

java - Java 中的 pretty-print JSON

ruby - 'json' 原生 gem 需要安装构建工具

json - 如何在构建 JSON 字符串时转义特殊字符?