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 = 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();

上一篇:16个时髦的扁平化设计的 HTML5 & CSS3 网站模板


下一篇:实用的PHP功能详解(一)_php glob()用法