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

Chr*_*ine 207 c# parsing json large-files

我已经花了两天时间对代码样本等进行"最好的"工作,尝试将一个非常大的JSON文件读入c#中的数组中,以便稍后将其拆分为二维数组进行处理.

我遇到的问题是我找不到任何人做我想做的事情的例子.这意味着我只是想编写一些希望最好的代码.

我已经成功地完成了一些工作:

  • 读取文件Miss out headers并仅将值读入数组.
  • 在数组的每一行上放置一定数量的值.(所以我以后可以把它分成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;
            }
    } 
}
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)

  • 对于那些不喜欢阅读其他答案的人来理解这个:这个解决方案需要Json.net包(Newtonsoft.Json) (19认同)
  • 在C#DotNet Core中,使用:using(StreamReader r = File.OpenText("file.json")) (13认同)
  • StreamReader("file.json")需要Stream不是字符串 (4认同)
  • @ChrisDevine 我希望你没有把路径写成 `json`。它必须是您文件的内容。 (2认同)
  • 由于无论如何你都有一个 `StreamReader`,最好使用 `JsonTextReader` 直接从流中反序列化,如 [Can Json.NET serialize / deserialize to / from a stream?](https://stackoverflow.com/ a/17788118)。不需要`r.ReadToEnd()`。 (2认同)

tme*_*ser 39

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

这是最好的:这次是懒惰并使用库,所以你永远解决这个常见问题.


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 文件结构复制并粘贴到左侧边栏中

应用程序.quicktype.io

3> 从选项菜单中选择所需的语言(此处为 C#)

4> 复制生成的代码并转到您的项目并创建一个具有相同名称的新 .cs 文件(此处为“Welcome.cs”)

欢迎.cs

5> 将所有生成的代码粘贴到新创建的类中。

Welcome.cs 粘贴代码

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)


sha*_*the 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; }        
 }
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 等获取您的对象。

  • 现在,您可以直接在 VS 中将 json 转换为 C#,“编辑”-&gt;“选择性粘贴”-&gt;“将 json 粘贴为类”。 (3认同)

Mar*_*ese 6

.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;
    }
}
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)


kuz*_*zdu 5

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

   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 并检查第一个路径末尾是否已有分隔符,因此不会重复分隔符。此外,它还会检查要组合的路径元素是否包含无效字符。

请参阅/sf/answers/2244970171/

  • 无论应用程序如何,找到绝对路径的更好方法:/sf/ask/1095774501/#23513793 (2认同)