.NET(C#) Json字符串反序列化成dynamic类型对象的方法代码

时间:2025-03-27 14:44:05

简介:

本文主要介绍.NET(C#)中,将Json字符串反序列化(Deserialize)时,反序列化(Deserialize)成动态类型(dynamic类型)对象的五种方法和代码。

1、使用实现

dynamic stuff = ("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = ;
string address = ;

//using 
dynamic stuff = ("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = ;
string address = ;

2、使用实现
包含在程序集(.NET 4.0)中。

var dynamicObject = ("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = ;
string address = ;

3、使用JavaScriptSerializer实现
.Net 4.0内置的一个库

using ;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = <dynamic>(str);

using ;
WebClient client = new WebClient();
string getString = ("/zuck");
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = <object>(getString);
string name = item["name"];

4、使用JsonFx实现

var reader = new JsonReader(); var writer = new JsonWriter();
string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = (input);
([0]); // 42
string json = (output);
(json); // {"foo":true,"array":[42,false,"Hello!",null]}

5、使用自定义DynamicJsonConverter类实现
需要引用
DynamicJsonConverter类代码:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
public sealed class DynamicJsonConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");
        return type == typeof(object) ? new DynamicJsonObject(dictionary) : 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[] { typeof(object) })); }
    }
    private sealed class DynamicJsonObject : DynamicObject
    {
        private readonly IDictionary<string, object> _dictionary;
        public DynamicJsonObject(IDictionary<string, object> dictionary)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");
            _dictionary = dictionary;
        }
        public override string ToString()
        {
            var sb = new StringBuilder("{");
            ToString(sb);
            return ();
        }
        private void ToString(StringBuilder sb)
        {
            var firstInDictionary = true;
            foreach (var pair in _dictionary)
            {
                if (!firstInDictionary)
                    (",");
                firstInDictionary = false;
                var value = ;
                var name = ;
                if (value is string)
                {
                    ("{0}:\"{1}\"", name, value);
                }
                else if (value is IDictionary<string, object>)
                {
                    new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
                }
                else if (value is ArrayList)
                {
                    (name + ":[");
                    var firstInArray = true;
                    foreach (var arrayValue in (ArrayList)value)
                    {
                        if (!firstInArray)
                            (",");
                        firstInArray = false;
                        if (arrayValue is IDictionary<string, object>)
                            new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
                        else if (arrayValue is string)
                            ("\"{0}\"", arrayValue);
                        else
                            ("{0}", arrayValue);
                    }
                    ("]");
                }
                else
                {
                    ("{0}:{1}", name, value);
                }
            }
            ("}");
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (!_dictionary.TryGetValue(, out result))
            {
                // return null to avoid exception.  caller can check for null this way...
                result = null;
                return true;
            }
            result = WrapResultObject(result);
            return true;
        }
        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            if ( == 1 && indexes[0] != null)
            {
                if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
                {
                    // return null to avoid exception.  caller can check for null this way...
                    result = null;
                    return true;
                }
                result = WrapResultObject(result);
                return true;
            }
            return (binder, indexes, out result);
        }
        private static object WrapResultObject(object result)
        {
            var dictionary = result as IDictionary<string, object>;
            if (dictionary != null)
                return new DynamicJsonObject(dictionary);
            var arrayList = result as ArrayList;
            if (arrayList != null &&  > 0)
            {
                return arrayList[0] is IDictionary<string, object> 
                    ? new List<object>(<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x))) 
                    : new List<object>(<object>());
            }
            return result;
        }
    }
}

使用示例代码:

dynamic data = ("{ \"Items\":[ { \"Name\":\"Apple\", \"Price\":12.3 }, { \"Name\":\"Grape\", \"Price\":3.21 } ], \"Date\":\"21/11/2010\" }", typeof(object));

; // "21/11/2010"
; // 2
[0].Name; // "Apple"
[0].Price; // 12.3 (as a decimal)
[1].Name; // "Grape"
[1].Price; // 3.21 (as a decimal)

了解更多分析及数据抓取可查看:
:8989/
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。