我花了两天时间“花时间”处理代码示例等,试图将一个非常大的 JSON 文件读入 c# 中的数组,以便以后可以将其拆分为二维数组进行处理。
我遇到的问题是我找不到任何人在做我想做的事情的例子。这意味着我只是在编辑代码,希望能做到最好。
我已经设法得到一些工作,将:
读取文件 Miss out headers 并且只将值读入数组。
在数组的每一行上放置一定数量的值。 (所以我可以稍后将其拆分为二维数组)
这是使用下面的代码完成的,但是在向数组中输入几行后它会使程序崩溃。这可能与文件大小有关。
// 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);
}
自己做这件事是个糟糕的主意。使用 Json.NET。如果他们有几个月的时间来解决这个问题,它已经比大多数程序员更好地解决了这个问题。至于您的特定需求,解析成数组等,请检查documentation,尤其是JsonTextReader
。基本上,Json.NET 原生处理 JSON 数组,并将它们解析为字符串、整数或任何类型的类型,而无需您提示。 Here 是读者和作者的基本代码用法的直接链接,因此您可以在学习使用它时在备用窗口中打开它。
这是最好的:这次要偷懒,使用库,这样你就可以永远解决这个常见问题。
.NET Core 的答案
您可以只使用内置 System.Text.Json
而不是第 3 方 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);
}
}
async Main
需要返回 Task
,而不是 void
。我更新了它。
这也可以通过以下方式完成:
JObject data = JObject.Parse(File.ReadAllText(MyFilePath));
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
}
基于@LB 的解决方案,(键入为 Object
而不是 Anonymous
)VB 代码是
Dim oJson As Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))
我应该提一下,这对于构建不需要类型的 HTTP 调用内容来说既快速又有用。使用 Object
而不是 Anonymous
意味着您可以在 Visual Studio 环境中维护 Option Strict On
- 我讨厌关闭它。
对于任何 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),以防您不想要任何第三方 DLL,如 newtonsoft。
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 等获取您的对象。
Edit
-> paste special
-> Paste json as Classes
。
为了找到我正在使用的正确路径
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 并检查第一个路径的末尾是否已经有分隔符,因此它不会重复分隔符。此外,它检查要组合的路径元素是否具有无效字符。
请参阅https://stackoverflow.com/a/32071002/4420355
有一种 比 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);
此代码可以帮助您:
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");
使用开源库 Cinchoo ETL,解析非常大的 JSON 文件是迭代的且易于使用
1.动态方法: - 不需要POCO类
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://dotnetfiddle.net/mo1qvw
2. POCO方法:
定义POCO类匹配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://dotnetfiddle.net/fRWu0w
免责声明:我是这个库的作者。
我在网上找到的在 C#(或任何其他编程语言)中使用 .JSON 文件的最简单方法
先决条件:-
将 Newtonsoft.Json 库安装到您的项目 Newtonsoft.Json
这是 URL -> https://app.quicktype.io/
脚步
1>转到此 URL - https://app.quicktype.io/
2> 将您的 JSON 文件结构复制并粘贴到左侧边栏中
3> 从选项菜单中选择所需的语言(此处为 C#)
4>复制生成的代码并转到您的项目并创建一个具有相同名称的新.cs文件(此处为“Welcome.cs”)
5> 将所有生成的代码粘贴到新创建的类中。
6> 就是这样。 :)
获取价值的步骤
1> 转到主程序 .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
}
}
不定期副业成功案例分享
json
。它必须是您文件的内容。StreamReader
,因此最好使用JsonTextReader
从流中直接反序列化,如 Can Json.NET serialize / deserialize to / from a stream? 所示。r.ReadToEnd()
不是必需的。