Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C语言中读取和解析Json文件#_C#_Json_Parsing_Large Files - Fatal编程技术网

C# 在C语言中读取和解析Json文件#

C# 在C语言中读取和解析Json文件#,c#,json,parsing,large-files,C#,Json,Parsing,Large Files,我花了两天的大部分时间“伪造”代码示例等,试图将一个非常大的JSON文件读入c#中的数组,以便以后可以将其拆分为2d数组进行处理 我遇到的问题是,我找不到任何人做我想做的事情的例子。这意味着我只是在编辑代码,希望能达到最好的效果 我已经设法让一些东西发挥作用,将: 读取文件漏读头并仅将值读入数组 在数组的每一行上放置一定数量的值。(所以我 以后可以将其拆分为二维阵列) 这是用下面的代码完成的,但在数组中输入几行代码后程序崩溃。这可能与文件大小有关 // If the file extensi

我花了两天的大部分时间“伪造”代码示例等,试图将一个非常大的JSON文件读入c#中的数组,以便以后可以将其拆分为2d数组进行处理

我遇到的问题是,我找不到任何人做我想做的事情的例子。这意味着我只是在编辑代码,希望能达到最好的效果

我已经设法让一些东西发挥作用,将:

  • 读取文件漏读头并仅将值读入数组
  • 在数组的每一行上放置一定数量的值。(所以我 以后可以将其拆分为二维阵列)
这是用下面的代码完成的,但在数组中输入几行代码后程序崩溃。这可能与文件大小有关

// 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文件,并且只提取我需要的数据并将其放入数组或我可以用来以后放入数组的东西。

自己这样做是个糟糕的主意。使用。它已经解决了这个问题,比大多数程序员能够更好地解决这个问题,如果他们连续几个月都能解决这个问题的话。至于您的特定需求,如解析为数组等,请查看,尤其是在
JsonTextReader
上。基本上,Json.NET以本机方式处理Json数组,并将它们解析为字符串、int或任何类型,而无需您的提示。是指向读写器的基本代码用法的直接链接,因此您可以在学习使用它时在备用窗口中打开该链接


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

用它让一切变得更容易怎么样

public void LoadJson()
{
使用(StreamReader r=newstreamreader(“file.json”))
{
字符串json=r.ReadToEnd();
List items=JsonConvert.DeserializeObject(json);
}
}
公共类项目
{
公共整数毫秒;
公众弦邮票;
公共日期时间;
公共弦灯;
公众浮标温度;
公共浮动vcc;
}
您甚至可以动态地获取值,而无需声明

dynamic array=JsonConvert.DeserializeObject(json);
foreach(数组中的变量项)
{
Console.WriteLine(“{0}{1}”,item.temp,item.vcc);
}

查找我正在使用的正确路径

   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 
Combine使用Path.PathSeparator,它检查第一条路径的末尾是否已经有分隔符,这样它就不会复制分隔符。此外,它还检查要合并的路径元素是否具有无效字符


请参见

基于@L.B.的解决方案,(键入为
对象
而不是
匿名
)VB代码是

Dim oJson As Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))
我应该提到,这对于构造不需要类型的HTTP调用内容是快速而有用的。使用
对象
而不是
匿名
意味着您可以在Visual Studio环境中严格维护
选项
——我讨厌关闭它。

string jsonFilePath=@“C:\MyFolder\myFile.json”;
字符串json=File.ReadAllText(jsonFilePath);
字典json_Dictionary=(新的JavaScriptSerializer())。反序列化(json);
foreach(json_字典中的var项)
{
//在这里解析
}

对于任何JSON解析,请使用网站(最简单的方法)将JSON转换为C#类,将JSON反序列化为C#对象

然后使用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);
}
使用(StreamReader r=newstreamreader(“jsonfile.json”))
{
字符串json=r.ReadToEnd();
JavaScriptSerializer jss=新的JavaScriptSerializer();
var Items=jss.Deserialize(json);
}

然后,您可以使用Items.name或Items.Url等获取对象。

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

JObject data = JObject.Parse(File.ReadAllText(MyFilePath));

此代码可以帮助您:

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

JObject data = JObject.Parse(_filePath );
NET内核的答案 您只需使用内置的
System.Text.Json
而不是第三方
Json.NET
。为了促进重用,JSON文件读取功能属于它自己的类,应该是通用的,而不是硬编码到某个类型(
Item
)。下面是一个完整的示例:

using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

namespace Project
{
    class Program
    {
        static async void 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;
    }
}
使用系统;
使用System.IO;
使用System.Text.Json;
使用System.Threading.Tasks;
命名空间项目
{
班级计划
{
静态异步void Main()
{
Item=wait jsonfillereader.ReadAsync(@“C:\myFile.json”);
}
}
公共静态类jsonfillereader
{
公共静态异步任务ReadAsync(字符串文件路径)
{
使用FileStream-stream=File.OpenRead(filePath);
返回等待JsonSerializer.DeserializeAsync(流);
}
}
公共类项目
{
公共整数毫秒;
公众弦邮票;
公共日期时间;
公共弦灯;
公众浮标温度;
公共浮动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);
    }
}
类程序
{
静态void Main()
{
Item=jsonfillereader.Read(@“C:\myFile.json”);
}
}
公共静态类jsonfillereader
{
公共静态T读(字符串文件路径)
{
string text=File.ReadAllText(文件路径);
返回JsonSerializer.Deserialize(文本);
}
}

程序崩溃时会抛出什么异常?这是否回答了您的问题?这回答了你的问题吗?我正在使用Json.net,但我不明白它是如何正确工作的。当我使用JsonTextReader将信息读入文本框时,我得到了每一点数据,但同时也感到头晕目眩
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);
    }
}