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

在程序集中找到 System.Runtime.Serialization ,選中后點擊確定。將 System.Runtime.Serialization 文件添加到項目引用中。

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)換成對象
/// </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>
/// 對象轉(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文件并且解析返回對應(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)換成對象
UDPRecData refData_UDP = JsonHandle.JsonToObject<UDPRecData>(richTextBox5.Text.ToString().Trim());
// JSON序列化:將對象轉(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);
}
}
}
此外,還需寫一個與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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c#實現(xiàn)幾種數(shù)據(jù)庫的大數(shù)據(jù)批量插入
這篇文章主要介紹了c#實現(xiàn)幾種數(shù)據(jù)庫的大數(shù)據(jù)批量插入,主要包括SqlServer、Oracle、SQLite和MySQL,有興趣的可以了解一下。2017-01-01
C#實現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號的方法
這篇文章主要介紹了C#實現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號的方法,比較實用的功能,需要的朋友可以參考下2014-07-07
c# WPF設(shè)置軟件界面背景為MediaElement并播放視頻
這篇文章主要介紹了c# WPF如何設(shè)置軟件界面背景為MediaElement并播放視頻,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03

