C#讀寫json文件操作的正確方法
一、JSON 文件
JSON(全稱為JavaScript Object Notation,JavaScript 對(duì)象表示法) 是一種輕量級(jí)的數(shù)據(jù)交換格式,用于存儲(chǔ)和交換文本信息的語(yǔ)法,類似 XML。它是基于JavaScript語(yǔ)法標(biāo)準(zhǔn)的一個(gè)子集,但它獨(dú)立于 JavaScript,因此許多程序環(huán)境能夠讀?。ń庾x)和生成 JSON。
JavaScript 對(duì)象表示法(JSON)是用于將結(jié)構(gòu)化數(shù)據(jù)表示為 JavaScript 對(duì)象的標(biāo)準(zhǔn)格式,通常用于在網(wǎng)站上表示和傳輸數(shù)據(jù)(例如從服務(wù)器向客戶端發(fā)送一些數(shù)據(jù),因此可以將其顯示在網(wǎng)頁(yè)上)。JSON 可以作為一個(gè)對(duì)象或者字符串存在,前者用于解讀 JSON 中的數(shù)據(jù),后者用于通過網(wǎng)絡(luò)傳輸 JSON 數(shù)據(jù)。
二、JSON 語(yǔ)法規(guī)則
JSON數(shù)據(jù)由鍵值對(duì)組成,每個(gè)鍵值對(duì)之間用逗號(hào)分隔,整個(gè)數(shù)據(jù)以大括號(hào) {} 包裹表示一個(gè)對(duì)象,或者以中括號(hào) [] 包裹表示一個(gè)數(shù)組?;菊Z(yǔ)法結(jié)構(gòu)如下:
1、對(duì)象(Object):使用大括號(hào) {} 包裹,鍵值對(duì)之間使用冒號(hào) : 分隔,如 { “name”: “John”, “age”: 30 }。
2、數(shù)組(Array):使用中括號(hào) [] 包裹,元素之間使用逗號(hào) , 分隔,如 [ “apple”, “banana”, “orange” ]。
3、使用斜桿 \ 來(lái)轉(zhuǎn)義字符。
4、大括號(hào) {} 保存對(duì)象,對(duì)象可以包含多個(gè)數(shù)組。
5、中括號(hào) [] 保存數(shù)組,數(shù)組可以包含多個(gè)對(duì)象。
三、JSON讀取操作類
1、添加 System.Runtime.Serialization 程序集文件
系統(tǒng)程序集文件中有能操作 JSON 文件的 API庫(kù)文件,在項(xiàng)目 “引用” 上右鍵,點(diǎn)擊“添加引用” ,打開“引用管理器”窗口。

在程序集中找到 System.Runtime.Serialization ,選中后點(diǎn)擊確定。將 System.Runtime.Serialization 文件添加到項(xiàng)目引用中。

2、JSON讀寫操作類
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace FileOperationsDemo
{
public static class JsonHandle
{
/// <summary>
/// Json轉(zhuǎn)換成對(duì)象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonText"></param>
/// <returns></returns>
public static T JsonToObject<T>(string jsonText)
{
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
T obj = (T)s.ReadObject(ms);
ms.Dispose();
return obj;
}
/// <summary>
/// 對(duì)象轉(zhuǎn)換成JSON
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ObjectToJSON<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
string result = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
ms.Position = 0;
using (StreamReader read = new StreamReader(ms))
{
result = read.ReadToEnd();
}
}
return result;
}
/// <summary>
/// 將序列化的json字符串內(nèi)容寫入Json文件,并且保存
/// </summary>
/// <param name="path">路徑</param>
/// <param name="jsonConents">Json內(nèi)容</param>
public static void WriteJsonFile(string path, string jsonConents)
{
if (!File.Exists(path)) // 判斷是否已有相同文件
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
{
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.WriteLine(jsonConents);
}
}
}
}
/// <summary>
/// 獲取到本地的Json文件并且解析返回對(duì)應(yīng)的json字符串
/// </summary>
/// <param name="filepath">文件路徑</param>
/// <returns>Json內(nèi)容</returns>
public static string GetJsonFile(string filepath)
{
string json = string.Empty;
using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
json = sr.ReadToEnd().ToString();
}
}
return json;
}
}
}
3、使用用例
/// <summary>
/// 讀取JSON文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button11_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Choose JSON File";
openFileDialog1.Filter = "JSON (*.json)|*.json";
openFileDialog1.Multiselect = false;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.InitialDirectory = dir;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// 獲取文件
string jsonTXT = JsonHandle.GetJsonFile(openFileDialog1.FileName);
richTextBox5.AppendText(jsonTXT + "\n");
}
}
/// <summary>
/// 寫入JSON文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button12_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(richTextBox5.Text.ToString().Trim()))
{
// JSON反序列化:將JSON 字符串轉(zhuǎn)換成對(duì)象
UDPRecData refData_UDP = JsonHandle.JsonToObject<UDPRecData>(richTextBox5.Text.ToString().Trim());
// JSON序列化:將對(duì)象轉(zhuǎn)換成JSON 字符串
string jsonFileDS = JsonHandle.ObjectToJSON<UDPRecData>(refData_UDP);
saveFileOpen.Title = "保存文件";
saveFileOpen.Filter = "JSON (*.json)|*.json";
saveFileOpen.RestoreDirectory = true;
saveFileOpen.InitialDirectory = dir;
saveFileOpen.FilterIndex = 1;
if (saveFileOpen.ShowDialog() == DialogResult.OK)
{
// 保存,輸出JSON文件
JsonHandle.WriteJsonFile(saveFileOpen.FileName, jsonFileDS);
}
}
}
此外,還需寫一個(gè)與JSON數(shù)據(jù)結(jié)構(gòu)一致的數(shù)據(jù)類。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace FileOperationsDemo
{
[DataContract]
public class UDPRecData
{
[DataMember(Order = 0)]
public Int32 id { get; set; }
[DataMember(Order = 1)]
public Identification ident { get; set; }
[DataMember(Order = 2)]
public TypeData type { get; set; }
[DataMember(Order = 3)]
}
[DataContract]
public class Identification
{
[DataMember(Order = 0)]
public string airline { get; set; }
[DataMember(Order = 1)]
public string reg { get; set; }
[DataMember(Order = 2)]
public string call { get; set; }
[DataMember(Order = 3)]
public string label { get; set; }
}
[DataContract]
public class TypeData
{
[DataMember(Order = 0)]
public string icao { get; set; }
[DataMember(Order = 1)]
public double wingSpan { get; set; }
[DataMember(Order = 2)]
public double wingArea { get; set; }
}
}
操作的JSON文件
{
"id" : 6711,
"ident" : {
"airline" : "DYH",
"reg" : "D-YVEL",
"call" : "llH1234",
"label" : "Test Temp"
},
"type" : {
"icao" : "Y72",
"wingSpan" : 11.1,
"wingArea" : 16.2
}
}

四、用字典提取Json
1、需要添加引用(System.Web.Extensions),用JavaScriptSerializer類(using System.Web.Script.Serialization;)反序列化,將字典作為類型提取JSON內(nèi)數(shù)據(jù)。
private void Deserialize()
{
jsonExplorer.Nodes.Clear();
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
Dictionary<string, object> dic = js.Deserialize<Dictionary<string, object>>(txtInput.Text);
TreeNode rootNode = new TreeNode("Root");
jsonExplorer.Nodes.Add(rootNode);
BuildTree(dic, rootNode);
}
catch (ArgumentException argE)
{
MessageBox.Show("JSON data is not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
2、通過嵌套循環(huán)讀取Json序列內(nèi)數(shù)組數(shù)據(jù),并將所有數(shù)據(jù)綁定到TreeView控件上。
public void BuildTree(Dictionary<string, object> dictionary, TreeNode node)
{
foreach (KeyValuePair<string, object> item in dictionary)
{
TreeNode parentNode = new TreeNode(item.Key);
node.Nodes.Add(parentNode);
try
{
dictionary = (Dictionary<string, object>)item.Value;
BuildTree(dictionary, parentNode);
}
catch (InvalidCastException dicE) {
try
{
ArrayList list = (ArrayList)item.Value;
foreach (string value in list)
{
TreeNode finalNode = new TreeNode(value);
finalNode.ForeColor = Color.Blue;
parentNode.Nodes.Add(finalNode);
}
}
catch (InvalidCastException ex)
{
TreeNode finalNode = new TreeNode(item.Value.ToString());
finalNode.ForeColor = Color.Blue;
parentNode.Nodes.Add(finalNode);
}
}
}
}總結(jié)
到此這篇關(guān)于C#讀寫json文件操作正確方法的文章就介紹到這了,更多相關(guān)C#讀寫json文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c#實(shí)現(xiàn)幾種數(shù)據(jù)庫(kù)的大數(shù)據(jù)批量插入
這篇文章主要介紹了c#實(shí)現(xiàn)幾種數(shù)據(jù)庫(kù)的大數(shù)據(jù)批量插入,主要包括SqlServer、Oracle、SQLite和MySQL,有興趣的可以了解一下。2017-01-01
C#之如何實(shí)現(xiàn)多個(gè)子窗體切換效果
這篇文章主要介紹了C#之如何實(shí)現(xiàn)多個(gè)子窗體切換的效果,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
C#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號(hào)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號(hào)的方法,比較實(shí)用的功能,需要的朋友可以參考下2014-07-07
c# WPF設(shè)置軟件界面背景為MediaElement并播放視頻
這篇文章主要介紹了c# WPF如何設(shè)置軟件界面背景為MediaElement并播放視頻,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
通過C#調(diào)用cmd來(lái)修改服務(wù)啟動(dòng)類型
可以使用System.ServiceProcess.ServiceController這個(gè)類允許連接到正在運(yùn)行或者已停止的服務(wù)、對(duì)其進(jìn)行操作或獲取有關(guān)它的信息但是這個(gè)類并沒有提供修改服務(wù)啟動(dòng)類型的方法,可以通過C#調(diào)用cmd來(lái)修改2012-12-12

