.net 4中使用 dynamic,将json字符串转成对象的 万能方法。

在.net 4中增加了对弱类型的支持。为和弱类型的对象进行数据交换提供了方法。我们常常会遇到将json字符串转成对象的情景,虽然可以使用

JavaScriptSerializer 或者 DataContractJsonSerializer

但是仍然需要些个对应的实体类,非常的麻烦。我在网上查资料,找到另外的实现方法:

使用:

string json = "[{\"name\":\"zhang3\"},{\"name\":\"zhang4\"}]";

var j = new JsonParser().FromJson(json);
//j是个 object[]
int len = j.Length;
var obj1 = j[0];
var name = j[1].name;

 

注意这里用到 dynamic 类型。在这里,弱类型的威力凸显出来了。

我们看看具体的实现类:

  /// <summary>
    /// json转换
    /// </summary>
    public class JsonParser {

        /// <summary>
        /// 从json字符串到对象。
        /// </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);
        }
    }

 

参考:

http://www.codeproject.com/Articles/349646/Dynamic-JSON-parser

http://msdn.microsoft.com/zh-cn/library/dd264736.aspx

http://www.oschina.net/question/89964_45078

http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4

posted on 2013-07-02 14:06  张云飞VIR  阅读(2570)  评论(0编辑  收藏  举报