Support for weak typing has been added in.NET 4. Provides a method for exchanging data with weakly typed objects. It is common to see json strings turned into objects, although it can be used

` JavaScriptSerializer 或者 DataContractJsonSerializer

‘But still need some corresponding entity class, very troublesome. I searched online and found another way to do it:

Use:

string json = "[{\"name\":\"zhang3\"},{\"name\":\"zhang4\"}]"; var j = new JsonParser().FromJson(json); //j is an object[] int len = j.length; var obj1 = j[0]; var name = j[1].name;Copy the code

 

Notice the use of dynamic here. This is where the power of the weak type comes into play.

Let’s look at the concrete implementation class:

/// <summary> // json conversion /// </summary> public class JsonParser {/// <summary> /// From JSON string to object. /// </summary> /// <param name="jsonStr"></param> /// <returns></returns> public dynamic FromJson(string jsonStr) { JavaScriptSerializer jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); dynamic glossaryEntry = jss.Deserialize(jsonStr, typeof(object)) as dynamic; return glossaryEntry; } } 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); }}Copy the code

 

Reference:

www.codeproject.com/Articles/34…

Msdn.microsoft.com/zh-cn/libra…

www.oschina.net/question/89…

Stackoverflow.com/questions/6…