非常に大きな JSON ファイルを C# の配列に読み込み、後で処理できるように分割するにはどうすればよいでしょうか?
私は、次のようなことを実行できるようになりました:
- ファイルを読み取り、ヘッダーを省略し、値のみを配列に読み込みます。
- 配列の各行に一定量の値を配置します。(後で分割して 2 次元配列に配置できるようにします)
これは以下のコードで実行されましたが、配列に数行入力した後、プログラムがクラッシュします。これはファイル サイズに関係している可能性があります。
// 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 ファイルを読み込んで、配列に入れる必要があるデータのみを抽出するにはどうすればよいでしょうか?
ベストアンサー1
すべてを簡単にするには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;
}
dynamically
クラスを宣言せずに値を取得することもできますItem
。
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}