C#Json总结,
写C#的多少会遇到JSON格式化,以下代码初步总结怎么使用。
以下两种方式均需引用Newtonsoft.Json.dll
一、使用JsonSerializer
class JosnUnit { public string Guid { get; set; } public string Index { get; set; } public string Title { get; set; } public string subTitle { get; set; } public string Type { get; set; } public string IsLeaf { get; set; } public string GroupName { get; set; } public string[] Children { get; set; } public string UserParam { get; set; } }using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace json解析 { class Program { static void Main(string[] args) { ; StreamReader streamReader = new StreamReader(path); //JsonReader reader = new JsonTextReader(streamReader); //while (reader.Read()) //{ // Console.WriteLine(reader.Value); //} JsonSerializer serializer = new JsonSerializer(); JosnUnit[] p1 = (JosnUnit[])serializer.Deserialize(new JsonTextReader(streamReader), typeof(JosnUnit[]));
streamReader.Dispose(); string str = p1[1].Guid; Console.ReadKey(); } } // "Guid":"40", //"Index":0, //"Title":"北侧2排电脑3", //"subTitle":"", //"Type":"32", //"IsLeaf":true, //"GroupName":"", //"Children":[ //], JosnUnit { public string Guid { get; set; } public string Index { get; set; } public string Title { get; set; } public string subTitle { get; set; } public string Type { get; set; } public string IsLeaf { get; set; } public string GroupName { get; set; } public string[] Children { get; set; } public string UserParam { get; set; } } }
二、使用JsonConvert
public class SignalModel { public string Guid { get; set; } public int Index { get; set; } public string Title { get; set; } public string subTitle { get; set; } public string Type { get; set; } public string GroupName { get; set; } public string Children { get; set; } public int UserParam { get; set; } }static void Main(string[] args) { List<SignalModel> pResult = new List<SignalModel>(); ; StreamReader streamReader = new StreamReader(path); var str=streamReader.ReadToEnd(); streamReader.Dispose(); str = str.Remove(str.Length - 1, 1);//删除结尾字符‘]’ str = str.Remove(0, 1);//删除开头字符‘[’ )) {
//去掉字符串中的‘[]’ str = str.Replace(, ); str = str.Replace(, ); str = + str + ;//首尾添加上‘[]’ List<SignalModel> modelList = JsonConvert.DeserializeObject<List<SignalModel>>(str); pResult = modelList; } Console.ReadKey(); }