码迷,mamicode.com
首页 > Web开发 > 详细

dynamic获取类型可变的json对象

时间:2016-12-28 07:48:32      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:names   line   mic   get   typeof   pos   oar   ***   type   

使用dynamic获取类型可变的json对象

Dictionary<string, object> dict = new Dictionary<string, object>();
List<dynamic> lst = new List<dynamic>() { new { aa = 1, bb = "2" } };
Type type = lst[0].GetType();
var ps = type.GetProperties();
string[] propertyNames = ps.Select(p => p.Name).ToArray();
foreach (var prop in propertyNames)
{
object propValue = type.GetProperty(prop).GetValue(lst[0], null);
string value = (propValue != null) ? propValue.ToString() : "";
if (!dict.ContainsKey(prop))
{
dict.Add(prop, value);
Console.WriteLine("prop:" + prop + ", value:" + value);
}
}

 

Console.WriteLine("*********************************************************");
var serializer = new JavaScriptSerializer();
string json = "{\"banme\":\"asd\"}";
dynamic data = serializer.Deserialize(json, typeof(object)) as dynamic;
var s = data.GetType().GetProperties();
dict.Clear();
foreach (var prop in data.Keys)
{
var value = data[prop];
if (!dict.ContainsKey(prop))
{
dict.Add(prop, value);
Console.WriteLine("prop:" + prop + ", value:" + value);
}
}
Console.Read();

dynamic获取类型可变的json对象

标签:names   line   mic   get   typeof   pos   oar   ***   type   

原文地址:http://www.cnblogs.com/Leo_wl/p/6228101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!