首页 > 代码库 > dynamic获取类型可变的json对象
dynamic获取类型可变的json对象
使用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 = http://www.mamicode.com/type.GetProperty(prop).GetValue(lst[0], null);
string value = http://www.mamicode.com/(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 = http://www.mamicode.com/serializer.Deserialize(json, typeof(object)) as dynamic;
var s = data.GetType().GetProperties();
dict.Clear();
foreach (var prop in data.Keys)
{
var value = http://www.mamicode.com/data[prop];
if (!dict.ContainsKey(prop))
{
dict.Add(prop, value);
Console.WriteLine("prop:" + prop + ", value:" + value);
}
}
Console.Read();
dynamic获取类型可变的json对象