JSON 轉成 C# 動態類

來源:互聯網
上載者:User

任意 JSON 轉成 C# 動態類,無需事先聲明一個C#類型,實現json字串轉成dynamic 類

樣本:

class Program
{
staticvoid Main(string[] args)
{
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;
}
}

用到兩個自訂的類:DynamicJsonConverter,DynamicJsonObject

代碼

publicclass DynamicJsonConverter : JavaScriptConverter
{
publicoverrideobject Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary ==null)
thrownew ArgumentNullException("dictionary");

if (type ==typeof(object))
{
returnnew DynamicJsonObject(dictionary);
}

returnnull;
}

publicoverride IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
thrownew NotImplementedException();
}

publicoverride IEnumerable<Type> SupportedTypes
{
get { returnnew ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
}
}

 

代碼

publicclass DynamicJsonObject : DynamicObject
{
private IDictionary<string, object> Dictionary { get; set; }

public DynamicJsonObject(IDictionary<string, object> dictionary)
{
this.Dictionary = dictionary;
}

publicoverridebool TryGetMember(GetMemberBinder binder, outobject result)
{
result =this.Dictionary[binder.Name];

if (result is IDictionary<string, object>)
{
result =new DynamicJsonObject(result as IDictionary<string, object>);
}
elseif (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>)));
}
elseif (result is ArrayList)
{
result =new List<object>((result as ArrayList).ToArray());
}

returnthis.Dictionary.ContainsKey(binder.Name);
}
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.