Chr*_*ine 207 c# parsing json large-files
我已经花了两天时间对代码样本等进行"最好的"工作,尝试将一个非常大的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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用的JSON片段是:
[
{ "millis": "1000",
"stamp": "1273010254",
"datetime": "2010/5/4 21:57:34",
"light": "333",
"temp": "78.32",
"vcc": "3.54" },
]
Run Code Online (Sandbox Code Playgroud)
我需要这个JSON的值.例如,我需要"3.54",但我不希望它打印"vcc".
我希望有人可以告诉我如何读取JSON文件并仅提取我需要的数据并将其放入数组或我可以用来以后放入数组的东西.
L.B*_*L.B 437
如何让所有事情变得更容易?
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;
}
Run Code Online (Sandbox Code Playgroud)
您甚至可以在dynamic不声明Item类的情况下获得值.
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}
Run Code Online (Sandbox Code Playgroud)
Adr*_*rma 20
这也可以通过以下方式完成:
JObject data = JObject.Parse(File.ReadAllText(MyFilePath));
Run Code Online (Sandbox Code Playgroud)
小智 13
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
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*inq 11
基于@LB的解决方案,(类型Object而不是Anonymous)VB代码是
Dim oJson As Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))
Run Code Online (Sandbox Code Playgroud)
我应该提一下,这对于构建不需要类型的HTTP调用内容非常快速且有用.使用Object而不是Anonymous手段可以Option Strict On在Visual Studio环境中维护- 我讨厌将其关闭.
小智 8
我在网上找到的用 C#(或任何其他编程语言)处理 .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
}
}
Run Code Online (Sandbox Code Playgroud)
对于任何 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; }
}
Run Code Online (Sandbox Code Playgroud)
然后使用 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);
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用 Items.name 或 Items.Url 等获取您的对象。
您可以只使用内置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;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您更喜欢更简单/同步的东西:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
为了找到我正在使用的正确路径
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
Run Code Online (Sandbox Code Playgroud)
Path.Combine 使用 Path.PathSeparator 并检查第一个路径末尾是否已有分隔符,因此不会重复分隔符。此外,它还会检查要组合的路径元素是否包含无效字符。
| 归档时间: |
|
| 查看次数: |
492689 次 |
| 最近记录: |