[英]Read and parse a Json File in C#
我花了兩天的大部分時間“花時間”研究代碼示例等,試圖將一個非常大的 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
類的情況下dynamically
獲取值。
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}
這也可以通過以下方式完成:
JObject data = JObject.Parse(File.ReadAllText(MyFilePath));
基於@LB 的解決方案,(類型為Object
而不是Anonymous
)VB 代碼是
Dim oJson As Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))
我應該提到,這對於構建不需要類型的 HTTP 調用內容是快速且有用的。 使用Object
而不是Anonymous
意味着您可以在 Visual Studio 環境中保持Option Strict On
- 我討厭關閉它。
string jsonFilePath = @"C:\MyFolder\myFile.json";
string json = File.ReadAllText(jsonFilePath);
Dictionary<string, object> json_Dictionary = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json);
foreach (var item in json_Dictionary)
{
// parse here
}
對於任何 JSON 解析,請使用網站http://json2csharp.com/ (最簡單的方法)將您的 JSON 轉換為 C# 類,以將您的 JSON 反序列化為 C# 對象。
public class JSONClass
{
public string name { get; set; }
public string url { get; set; }
public bool visibility { get; set; }
public string idField { get; set; }
public bool defaultEvents { get; set; }
public string type { get; set; }
}
然后使用 JavaScriptSerializer(來自 System.Web.Script.Serialization),以防您不想要任何像 newtonsoft 這樣的第三方 DLL。
using (StreamReader r = new StreamReader("jsonfile.json"))
{
string json = r.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
var Items = jss.Deserialize<JSONClass>(json);
}
然后您可以使用 Items.name 或 Items.Url 等獲取您的對象。
我在網上找到的使用 C#(或任何其他編程語言)處理 .JSON 文件的最簡單方法
先決條件: -
這是 URL -> https://app.quicktype.io/
腳步
1> go 到這個 URL - https://app.quicktype.io/
2> 將 JSON 文件結構復制並粘貼到左側欄
3> Select 需要選項菜單中的語言(此處為 C#)
4> 將生成的代碼和 go 復制到您的項目並創建一個具有相同名稱的新.cs 文件(此處為“Welcome.cs”)
5> 將所有生成的代碼粘貼到新建的class中。
6> 就是這樣。 :)
獲取價值的步驟
1> Go 到 Main Program.cs 文件或任何你需要訪問它的地方。
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Access Json values using Keys.>");
String jsonString = new StreamReader("give <.json> file Path here").ReadToEnd();
// use below syntax to access JSON file
var jsonFile = Welcome.FromJson(jsonString);
string FileName = jsonFile.File;
long Lvl = jsonFile.Level;
bool isTrue = jsonFile.CSharp;
Console.WriteLine(FileName);//JSON
Console.WriteLine(Lvl);//1
Console.WriteLine(isTrue);//true
}
}
您可以只使用內置System.Text.Json
而不是 3rd-party Json.NET
。 為了促進重用,JSON 文件讀取功能屬於它自己的類,應該是通用的,而不是硬編碼到某種類型 ( Item
)。 這是一個完整的例子:
using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
namespace Project
{
class Program
{
static async Task Main()
{
Item item = await JsonFileReader.ReadAsync<Item>(@"C:\myFile.json");
}
}
public static class JsonFileReader
{
public static async Task<T> ReadAsync<T>(string filePath)
{
using FileStream stream = File.OpenRead(filePath);
return await JsonSerializer.DeserializeAsync<T>(stream);
}
}
public class Item
{
public int millis;
public string stamp;
public DateTime datetime;
public string light;
public float temp;
public float vcc;
}
}
或者,如果您更喜歡更簡單/同步的東西:
class Program
{
static void Main()
{
Item item = JsonFileReader.Read<Item>(@"C:\myFile.json");
}
}
public static class JsonFileReader
{
public static T Read<T>(string filePath)
{
string text = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<T>(text);
}
}
為了找到我正在使用的正確路徑
var pathToJson = Path.Combine("my","path","config","default.Business.Area.json");
var r = new StreamReader(pathToJson);
var myJson = r.ReadToEnd();
// my/path/config/default.Business.Area.json
[...] do parsing here
Path.Combine 使用 Path.PathSeparator 並檢查第一個路徑是否已經在末尾有一個分隔符,因此它不會重復分隔符。 此外,它還會檢查要組合的路徑元素是否具有無效字符。
此代碼可以幫助您:
string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
JObject data = JObject.Parse(_filePath );
有一種更簡單的方法可以從文件或 Web 中獲取 JSON: Json.Net.Curl
安裝包 Json.Net.Curl
// get JObject from local file system
var json = Json.Net.Curl.Get(@"data\JObjectUnitTest1.json");
var json = await Json.Net.Curl.GetAsync(@"data\JObjectUnitTest1.json")
// get JObject from Server
var json = await Json.Net.Curl.GetAsync("http://myserver.com/data.json");
有一種比Json.Net更快的解析 json 的方法。 如果您使用 .net core 3.0 或更高版本,則可以使用System.Text.Json nuget 包進行序列化或反序列化。
你需要添加:
using System.Text.Json
然后你可以序列化為:
var jsonStr = JsonSerializer.Serialize(model);
並反序列化為:
var model = JsonSerializer.Deserialize(jsonStr);
使用開源庫Cinchoo ETL迭代解析超大 JSON 文件,使用簡單
1. 動態方法: - 無需 POCO class
string json = @"
[
{
""millis"": ""1000"",
""stamp"": ""1273010254"",
""datetime"": ""2010/5/4 21:57:34"",
""light"": ""333"",
""temp"": ""78.32"",
""vcc"": ""3.54""
},
{
""millis"": ""2000"",
""stamp"": ""1273010254"",
""datetime"": ""2010/5/4 21:57:34"",
""light"": ""333"",
""temp"": ""78.32"",
""vcc"": ""3.54""
}
]
";
using (var r = ChoJSONReader.LoadText(json))
{
foreach (var rec in r)
Console.WriteLine(rec.Dump());
}
示例小提琴: https://do.netfiddle.net/mo1qvw
2.POCO方法:
定義 POCO class 匹配 json 屬性
public class Item
{
public int Millis { get; set; }
public string Stamp { get; set; }
public DateTime Datetime { get; set; }
public string Light { get; set; }
public float Temp { get; set; }
public float Vcc { get; set; }
}
然后使用解析器加載 JSON,如下所示
string json = @"
[
{
""millis"": ""1000"",
""stamp"": ""1273010254"",
""datetime"": ""2010/5/4 21:57:34"",
""light"": ""333"",
""temp"": ""78.32"",
""vcc"": ""3.54""
},
{
""millis"": ""2000"",
""stamp"": ""1273010254"",
""datetime"": ""2010/5/4 21:57:34"",
""light"": ""333"",
""temp"": ""78.32"",
""vcc"": ""3.54""
}
]
";
using (var r = ChoJSONReader<Item>.LoadText(json))
{
foreach (var rec in r)
Console.WriteLine(ChoUtility.Dump(rec));
}
示例小提琴: https://do.netfiddle.net/fRWu0w
免責聲明:我是這個圖書館的作者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.