写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) { string path = AppDomain.CurrentDomain.BaseDirectory + "\\信号源列表.txt"; 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":[ //], //"UserParam":"2" 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; } } }
二、使用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>(); string path = AppDomain.CurrentDomain.BaseDirectory + "\\信号源列表.txt"; StreamReader streamReader = new StreamReader(path); var str=streamReader.ReadToEnd(); streamReader.Dispose(); str = str.Remove(str.Length - 1, 1);//删除结尾字符‘]’ str = str.Remove(0, 1);//删除开头字符‘[’ if (!string.IsNullOrEmpty(str) && str.Contains("subTitle")) {
//去掉字符串中的‘[]’ str = str.Replace("[", "\""); str = str.Replace("]", "\""); str = "[" + str + "]";//首尾添加上‘[]’ List<SignalModel> modelList = JsonConvert.DeserializeObject<List<SignalModel>>(str); pResult = modelList; } Console.ReadKey(); }
第二种方式发现使用JsonConvert我发现里面字符串除了开头可以有'[]',中间不能有,否则报错,而第一种方式却正常,后来才发现原来字符串中Children字段应该是集合类型,因为里面含有“[]”。而我的SignalModel类却只把他定义成string类型,当然Json化会报错。第一种中JosnUnit类里将Children定义成数组类型所以不会报错。
以上是自己水平菜的时候踩的一个坑,仅供参考。