C#解析JSON

  C#解析JSON一直是一个很头疼的事情,网上各种资料都比较旧,于是不知道某天我找到了一个比较好的方法,分享如下

  走来先要打开NuGet,搜索Newtonsoft.Json,然后安装。这是一个很优秀的Json解析库,非常优秀,优秀的飞起!

  然后定义好一个数据契约(DataContract),嗯~一个类就可以了。

  最后用下面的代码进行解析,还是蛮简单的。

 1         public static T JsonDecode<T>(string PathOrData)
 2         {
3        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
4 JsonSerializer json = new JsonSerializer(); 5 json.NullValueHandling = NullValueHandling.Ignore; 6 json.ObjectCreationHandling = ObjectCreationHandling.Replace; 7 json.MissingMemberHandling = MissingMemberHandling.Ignore; 8 json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 9 TextReader Stream = null; 10 try 11 { 12 IsolatedStorageFileStream Location = new IsolatedStorageFileStream(PathOrData, FileMode.Open, storage); 13 Stream = (TextReader)new StreamReader(Location); 14 } 15 catch (Exception e) 16 { 17 Stream = (TextReader)new StringReader(PathOrData); 18 } 19 JsonTextReader Reader = new JsonTextReader(Stream); 20 T Result = (T)json.Deserialize(Reader, typeof(T)); 21 Reader.Close(); 22 return Result; 23 }
原文地址:https://www.cnblogs.com/toruneko/p/3278607.html