为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
哈士奇WWW 2019-10-15 15:05:32
我花了两天的大部分时间来“打理”代码示例等,试图将一个非常大的JSON文件读入c#中的数组,以便稍后将其拆分为2d数组进行处理。我遇到的问题是我找不到任何人在做我想做的事的例子。这意味着我只是在编辑代码,以期获得最佳效果。我设法使某些东西能够工作:读取文件Missing out标头,仅将值读入数组。在数组的每一行上放置一定数量的值。(所以我以后可以将它分割成2d数组)这是用下面的代码完成的,但是在数组中输入几行后,它使程序崩溃。这可能与文件大小有关。// 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 statementif (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文件,并且仅提取所需的数据并将其放入数组中,或以后可用于放入数组中的内容。
查看完整描述

3 回答

?
大话西游666

TA贡献1817条经验 获得超14个赞

根据@LB的解决方案,(键入为Object而不是Anonymous)VB代码为


Dim oJson as Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))

我应该提到,这对于构造不需要类型的HTTP调用内容是快速且有用的。使用Object而不是Anonymous意味着您可以Option Strict On在Visual Studio环境中进行维护-我讨厌将其关闭。


查看完整回答
反对 回复 2019-10-15
  • 3 回答
  • 0 关注
  • 2218 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信