Newtonsoft.Json 获取匿名类数据
很简单。
1 using System; 2 using System.Collections.Generic; 3 4 namespace Test 5 { 6 class Program 7 { 8 9 static string Message = "{\"Result\":0,\"ErrMsg\":\"执行失败。索引超出范围。必须为非负值并小于集合大小。\r\n参数名: index\",\"ErrCode\":\"\"}"; 10 11 static void Main(string[] args) 12 { 13 var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(Message) as Newtonsoft.Json.Linq.JObject; 14 15 foreach (var item in obj) 16 { 17 Console.WriteLine(item.Value); 18 } 19 20 Console.Read(); 21 } 22 } 23 }
加红的那句,将匿名类转换成Newtonsoft内置的Object,以便获取值。
而内置Object将数据以List<JToken>形式存储。可以使用循环直接获取值。
补充:
关于匿名数组类处理
1 var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(Message); 2 var tmpType= obj.GetType(); 3 var arrayType= typeof(Newtonsoft.Json.Linq.JArray); 4 if (tmpType==arrayType) 5 { 6 var tmpObj = obj as Newtonsoft.Json.Linq.JArray; 7 foreach (var item in tmpObj) 8 { 9 Console.WriteLine(item.HasValues); 10 } 11 } 12 else 13 { 14 var tmpObj = obj as Newtonsoft.Json.Linq.JObject; 15 foreach (var item in tmpObj) 16 { 17 Console.WriteLine(item.Value); 18 } 19 }
先将数据转换,Newtonsoft自动会识别字符串内容,进行转换,若为数组则其类型为JArray。
通过判断类型,分别处理数据。