dynamic
var url = "http://localhost:24334/api/UserApi"; var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (var http = new HttpClient(handler)) { //await异步等待回应
var response = http.GetAsync(url);
//将服务端返回的实体序列化为dynamic动态类
var obj = JsonConvert.DeserializeObject<dynamic>(response.Result.Content.ReadAsStringAsync().Result);
//遍历这个动态集合
foreach (var item in obj)
{
return Content("userName:" + item.UserName);
}
}
public static class IDictionaryExtensions { public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary) { var expando = new ExpandoObject(); var expandoDic = (IDictionary<string, object>)expando; // go through the items in the dictionary and copy over the key value pairs) foreach (var kvp in dictionary) { // if the value can also be turned into an ExpandoObject, then do it! if (kvp.Value is IDictionary<string, object>) { var expandoValue = ((IDictionary<string, object>)kvp.Value).ToExpando(); expandoDic.Add(kvp.Key, expandoValue); } else if (kvp.Value is ICollection) { // iterate through the collection and convert any strin-object dictionaries // along the way into expando objects var itemList = new List<object>(); foreach (var item in (ICollection)kvp.Value) { if (item is IDictionary<string, object>) { var expandoItem = ((IDictionary<string, object>)item).ToExpando(); itemList.Add(expandoItem); } else { itemList.Add(item); } } expandoDic.Add(kvp.Key, itemList); } else { expandoDic.Add(kvp); } } return expando; } }
dynamic test = new ExpandoObject(); test.x = "xvalue"; test.y = DateTime.Now; JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string jsonOfTest = javaScriptSerializer.Serialize(test); // [{"Key":"x","Value":"xvalue"},{"Key":"y","Value":"\/Date(1314108923000)\/"}] /// <summary> /// Allows JSON serialization of Expando objects into expected results (e.g., "x: 1, y: 2") instead of the default dictionary serialization. /// </summary> public class ExpandoJsonConverter : JavaScriptConverter { public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { // See source code link for this extension method at the bottom of this post (/Helpers/IDictionaryExtensions.cs) return dictionary.ToExpando(); } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { var result = new Dictionary<string, object>(); var dictionary = obj as IDictionary<string, object>; foreach (var item in dictionary) result.Add(item.Key, item.Value); return result; } public override IEnumerable<Type> SupportedTypes { get { return new ReadOnlyCollection<Type>(new Type[] { typeof(ExpandoObject) }); } } } JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); javaScriptSerializer.RegisterConverters(new JavaScriptConverter[] { new ExpandoJsonConverter() }); jsonOfTest = javaScriptSerializer.Serialize(test); // {"x":"xvalue","y":"\/Date(1314108923000)\/"}
http://blog.csdn.net/zuoyuyi/article/details/51452360
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class DynamicJsonConverter : JavaScriptConverter { public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (type == typeof(object)) { return new DynamicJsonObject(dictionary); } return null; } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { throw new NotImplementedException(); } public override IEnumerable<Type> SupportedTypes { get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); } } } public class DynamicJsonObject : DynamicObject { private IDictionary<string, object> Dictionary { get; set; } public DynamicJsonObject(IDictionary<string, object> dictionary) { this.Dictionary = dictionary; } public override bool TryGetMember(GetMemberBinder binder, out object result) { result = this.Dictionary[binder.Name]; if (result is IDictionary<string, object>) { result = new DynamicJsonObject(result as IDictionary<string, object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>) { result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>))); } else if (result is ArrayList) { result = new List<object>((result as ArrayList).ToArray()); } return this.Dictionary.ContainsKey(binder.Name); } }
string json = "{name:'hooyes',pwd:'hooyespwd',books:{a:'红楼梦',b:'水浒传',c:{arr:['宝玉','林黛玉']}},arr:['good','very good']}"; dynamic dy = ConvertJson(json); Console.WriteLine(dy.name); Console.WriteLine(dy.books.a); Console.WriteLine(dy.arr[1]); foreach (var s in dy.books.c.arr) { Console.WriteLine(s); } Console.Read(); static dynamic ConvertJson(string json) { JavaScriptSerializer jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); dynamic dy = jss.Deserialize(json, typeof(object)) as dynamic; return dy; }