323

我花了两天时间“花时间”处理代码示例等,试图将一个非常大的 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 文件并仅提取我需要的数据并将其放入数组或稍后我可以使用的东西放入数组中。

4

12 回答 12

606

使用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);
    }
于 2012-11-08T21:18:01.757 回答
48

自己做这件事是个糟糕的主意。使用Json.NET。如果他们有几个月的时间来解决这个问题,它已经比大多数程序员更好地解决了这个问题。至于您的特定需求,解析成数组等,请查看文档,特别是在JsonTextReader. 基本上,Json.NET 原生处理 JSON 数组,并将它们解析为字符串、整数或任何类型的类型,而无需您提示。 是读者和作者的基本代码用法的直接链接,因此您可以在学习使用它时在备用窗口中打开它。

这是最好的:这次要偷懒,使用库,这样你就可以永远解决这个常见问题。

于 2012-11-08T20:52:11.757 回答
23

这也可以通过以下方式完成:

JObject data = JObject.Parse(File.ReadAllText(MyFilePath));
于 2020-04-17T11:37:31.557 回答
19

.NET Core 的答案

您可以只使用内置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);
    }
}
于 2021-06-09T19:25:25.647 回答
15

基于@LB的解决方案,(键入Object而不是Anonymous)VB代码是

Dim oJson As Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))

我应该提一下,这对于构建不需要类型的 HTTP 调用内容来说既快速又有用。并且使用Object而不是Anonymous意味着您可以Option Strict On在 Visual Studio 环境中维护 - 我讨厌将其关闭。

于 2018-06-19T21:26:23.637 回答
14
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
}
于 2019-07-05T06:09:23.313 回答
7

对于任何 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 等获取您的对象。

于 2019-10-08T14:41:37.083 回答
4

为了找到我正在使用的正确路径

   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

于 2018-01-25T13:52:05.593 回答
3

有一种比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);
于 2021-06-17T13:59:41.473 回答
1

此代码可以帮助您:

string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

JObject data = JObject.Parse(_filePath );
于 2020-08-10T08:48:01.150 回答
1

有一种更简单的方法可以从文件或 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");

GitHub 项目 Nuget

于 2021-07-11T13:47:39.643 回答
0

使用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

免责声明:我是这个库的作者。

于 2021-09-21T16:40:44.393 回答