一、json 文件
json(全称为javascript object notation,javascript 对象表示法) 是一种轻量级的数据交换格式,用于存储和交换文本信息的语法,类似 xml。它是基于javascript语法标准的一个子集,但它独立于 javascript,因此许多程序环境能够读取(解读)和生成 json。
javascript 对象表示法(json)是用于将结构化数据表示为 javascript 对象的标准格式,通常用于在网站上表示和传输数据(例如从服务器向客户端发送一些数据,因此可以将其显示在网页上)。json 可以作为一个对象或者字符串存在,前者用于解读 json 中的数据,后者用于通过网络传输 json 数据。
二、json 语法规则
json数据由键值对组成,每个键值对之间用逗号分隔,整个数据以大括号 {} 包裹表示一个对象,或者以中括号 [] 包裹表示一个数组。基本语法结构如下:
1、对象(object):使用大括号 {} 包裹,键值对之间使用冒号 : 分隔,如 { “name”: “john”, “age”: 30 }。
2、数组(array):使用中括号 [] 包裹,元素之间使用逗号 , 分隔,如 [ “apple”, “banana”, “orange” ]。
3、使用斜杆 \ 来转义字符。
4、大括号 {} 保存对象,对象可以包含多个数组。
5、中括号 [] 保存数组,数组可以包含多个对象。
三、json读取操作类
1、添加 system.runtime.serialization 程序集文件
系统程序集文件中有能操作 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转换成对象 /// </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> /// 对象转换成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字符串内容写入json文件,并且保存 /// </summary> /// <param name="path">路径</param> /// <param name="jsonconents">json内容</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文件并且解析返回对应的json字符串 /// </summary> /// <param name="filepath">文件路径</param> /// <returns>json内容</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 字符串转换成对象 udprecdata refdata_udp = jsonhandle.jsontoobject<udprecdata>(richtextbox5.text.tostring().trim()); // json序列化:将对象转换成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数据结构一致的数据类。
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内数据。
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、通过嵌套循环读取json序列内数组数据,并将所有数据绑定到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); } } } }
总结
到此这篇关于c#读写json文件操作正确方法的文章就介绍到这了,更多相关c#读写json文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论