在 C# 中读取和解析 Json 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13297563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read and parse a Json File in C#
提问by Chris Devine
I have spent the best part of two days "faffing" about with code samples and etc., trying to read a very large JSON file into an array in c# so I can later split it up into a 2d array for processing.
我花了两天的大部分时间来“处理”代码示例等,试图将一个非常大的 JSON 文件读入 c# 中的数组,以便稍后将其拆分为二维数组进行处理。
The problem I was having was I could not find any examples of people doing what I was trying to do. This meant I was just editing code a little an hoping for the best.
我遇到的问题是我找不到任何人做我想做的事情的例子。这意味着我只是在编辑代码,并希望得到最好的结果。
I have managed to get something working that will:
我已经设法使一些工作能够:
- Read the file Miss out headers and only read values into array.
- Place a certain amount of values on each line of an array. (So I could later split it an put into 2d array)
- 读取文件错过标题,只将值读入数组。
- 在数组的每一行上放置一定数量的值。(所以我以后可以将它拆分为二维数组)
This was done with the code below but it crashes the program after entering a few lines into the array. This might have to do with the file size.
这是通过下面的代码完成的,但在向数组中输入几行后它会导致程序崩溃。这可能与文件大小有关。
// 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;
}
}
}
A snippet of the JSON I am working with is:
我正在使用的 JSON 片段是:
[
{ "millis": "1000",
"stamp": "1273010254",
"datetime": "2010/5/4 21:57:34",
"light": "333",
"temp": "78.32",
"vcc": "3.54" },
]
I need the values out of this JSON. For example, I need "3.54", but I would not want it to print the "vcc".
我需要这个 JSON 中的值。例如,我需要“3.54”,但我不希望它打印“vcc”。
I am hoping someone can show me how to read a JSON file in and only extract the data that I need and put it into an array or something that I can use to later put into an array.
我希望有人能告诉我如何读取 JSON 文件,并且只提取我需要的数据并将其放入数组或稍后我可以用来放入数组的内容。
回答by tmesser
Doing this yourself is an awful idea. Use Json.NET. It has already solved the problem better than most programmers could if they were given months on end to work on it. As for your specific needs, parsing into arrays and such, check the documentation, particularly on JsonTextReader. Basically, Json.NET handles JSON arrays natively and will parse them into strings, ints, or whatever the type happens to be without prompting from you. Hereis a direct link to the basic code usages for both the reader and the writer, so you can have that open in a spare window while you're learning to work with this.
自己这样做是一个糟糕的主意。使用Json.NET。如果让大多数程序员连续数月来解决这个问题,它已经比大多数程序员更好地解决了这个问题。至于您的特定需求,解析为数组等,请查看文档,尤其是JsonTextReader. 基本上,Json.NET 以本机方式处理 JSON 数组,并将它们解析为字符串、整数或任何碰巧的类型,而无需您提示。 这是读者和作者的基本代码用法的直接链接,因此您可以在学习使用它时在备用窗口中打开它。
This is for the best: Be lazy this time and use a library so you solve this common problem forever.
这是最好的:这次偷懒并使用库,这样您就可以永远解决这个常见问题。
回答by L.B
How about making all the things easier with Json.NET?
使用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;
}
You can even get the values dynamically without declaring Itemclass.
您甚至可以在dynamic不声明Item类的情况下获得值盟友。
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}
回答by kuzdu
For finding the right path I'm using
为了找到我正在使用的正确路径
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 uses the Path.PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.
Path.Combine 使用 Path.PathSeparator 并检查第一个路径是否已经在末尾有一个分隔符,因此它不会重复分隔符。此外,它还会检查要组合的路径元素是否具有无效字符。
回答by SteveCinq
Based on @L.B.'s solution, the (typed as Objectrather than Anonymous) VB code is
基于@LB 的解决方案,(类型为Object而不是Anonymous)VB 代码是
Dim oJson As Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))
I should mention that this is quick and useful for constructing HTTP call content where the type isn't required. And using Objectrather than Anonymousmeans you can maintain Option Strict Onin your Visual Studio environment - I hate turning that off.
我应该提到,这对于构建不需要类型的 HTTP 调用内容是快速且有用的。使用Object而不是Anonymous意味着您可以Option Strict On在 Visual Studio 环境中进行维护- 我讨厌关闭它。
回答by Kanad Mehta
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
}
回答by shailesh gavathe
For any of the JSON parse, use the website http://json2csharp.com/(easiest way) to convert your JSON into C# class to deserialize your JSON into C# object.
对于任何 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; }
}
Then use the JavaScriptSerializer (from System.Web.Script.Serialization), in case you don't want any third party DLL like newtonsoft.
然后使用 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);
}
Then you can get your object with Items.name or Items.Url etc.
然后您可以使用 Items.name 或 Items.Url 等获取您的对象。
回答by Adrita Sharma
This can also be done in the following way:
这也可以通过以下方式完成:
JObject data = JObject.Parse(File.ReadAllText(MyFilePath));

![使用 [JsonProperty] 将 Json 参数与类型为 List 的 C# 类属性匹配](/res/img/loading.gif)