我花了两天的大部分时间来处理代码示例等问题,试图用c#将一个非常大的JSON文件读入一个数组,以便稍后可以将其拆分成一个二维数组进行处理。
我遇到的问题是,我找不到任何人做我想做的事情的例子。这意味着我只是稍微编辑了一下代码,并抱着最好的希望。
我已经设法让一些东西工作起来,它将:
这是使用下面的代码完成的,但它在数组中输入几行代码后使程序崩溃。这可能与文件大小有关。
// 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文件,只提取我需要的数据,并将其放入一个数组中,或者其他我可以用来放入数组中的东西。
发布于 2012-11-09 05:18:02
使用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
类的情况下获得值dynamically
。
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}
发布于 2012-11-09 04:52:12
自己做这件事是个糟糕的主意。使用Json.NET。它已经比大多数程序员更好地解决了这个问题,如果他们有几个月的时间来处理它的话。对于您的特定需求,解析为数组之类的,请检查documentation,特别是在JsonTextReader
上。基本上,Json.NET在本地处理JSON数组,并将它们解析为字符串、整数或任何类型,而不需要您的提示。Here是读者和编写者基本代码用法的直接链接,因此您可以在学习使用它的同时在一个空闲窗口中打开它。
这是最好的:这一次要懒惰,使用一个库,这样你就可以永远解决这个常见的问题。
发布于 2020-04-17 19:37:32
这也可以通过以下方式完成:
JObject data = JObject.Parse(File.ReadAllText(MyFilePath));
https://stackoverflow.com/questions/13297563
复制相似问题