是否有方法将JSON内容反序列化为c#动态类型?为了使用DataContractJsonSerializer,最好跳过创建一堆类。


当前回答

我需要的是返回一个带有不同字段的json模型。 我的模型是这样的,但它可以改变。

{
    "employees":
    [
        { "name": "Darth", "surname": "Vader", "age": "27", "department": "finance"},
        { "name": "Luke", "surname": "Skywalker", "age": "25", "department": "IT"},
        { "name": "Han", "surname": "Solo", "age": "26", "department": "credit"}
    ]
}

获取数据值的列表

    JObject array = JObject.Parse(model.JsonData);
    var tableData = new List<JsonDynamicModel>();

    foreach (var objx in array.Descendants().OfType<JProperty>().Where(p => p.Value.Type != JTokenType.Array && p.Value.Type != JTokenType.Object))
            {
                var name = ((JValue)objx.Name).Value;
                var value = ((JValue)objx.Value).Value;
                if (tableData.FirstOrDefault(x => x.ColumnName == name.ToString()) == null)
                {
                    tableData.Add(new JsonDynamicModel
                    {
                        ColumnName = name.ToString(),
                        Values = new List<string> { value.ToString() },
                    });
                }
                else
                {
                    tableData.FirstOrDefault(x=>x.ColumnName == name.ToString()).Values.Add(value.ToString());
                }
            }

输出如下所示。然后我把结果模型转换成一个html表,我用这个方法创建了一个html表

// output
tableData[0].ColumnName -> "name";
tableData[0].Values -> {"Darth", "Luke", "Han" }
tableData[1].ColumnName -> "surname";
tableData[1].Values -> {"Vader", "Skywalker", "Solo" }
...

其他回答

使用Json非常简单。NET:

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

同样使用Newtonsoft.Json.Linq:

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

文档:使用动态查询JSON

如果你喜欢依赖System.Web.Helpers程序集,那么你可以使用Json类:

dynamic data = Json.Decode(json);

它作为。net 4框架的附加下载包含在MVC框架中。如果有用的话,一定要给弗拉德点赞!但是,如果您不能假定客户机环境包含这个DLL,那么请继续阅读。


这里建议使用另一种反序列化方法。我稍微修改了代码,以修复一个错误,并适合我的编码风格。所有你需要的是这段代码和从你的项目中引用System.Web.Extensions:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

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) })); }
    }

    #region Nested type: DynamicJsonObject

    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 sb.ToString();
        }

        private void ToString(StringBuilder sb)
        {
            var firstInDictionary = true;
            foreach (var pair in _dictionary)
            {
                if (!firstInDictionary)
                    sb.Append(",");
                firstInDictionary = false;
                var value = pair.Value;
                var name = pair.Key;
                if (value is string)
                {
                    sb.AppendFormat("{0}:\"{1}\"", name, value);
                }
                else if (value is IDictionary<string, object>)
                {
                    new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
                }
                else if (value is ArrayList)
                {
                    sb.Append(name + ":[");
                    var firstInArray = true;
                    foreach (var arrayValue in (ArrayList)value)
                    {
                        if (!firstInArray)
                            sb.Append(",");
                        firstInArray = false;
                        if (arrayValue is IDictionary<string, object>)
                            new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
                        else if (arrayValue is string)
                            sb.AppendFormat("\"{0}\"", arrayValue);
                        else
                            sb.AppendFormat("{0}", arrayValue);

                    }
                    sb.Append("]");
                }
                else
                {
                    sb.AppendFormat("{0}:{1}", name, value);
                }
            }
            sb.Append("}");
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (!_dictionary.TryGetValue(binder.Name, 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 (indexes.Length == 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 base.TryGetIndex(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 && arrayList.Count > 0)
            {
                return arrayList[0] is IDictionary<string, object> 
                    ? new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x))) 
                    : new List<object>(arrayList.Cast<object>());
            }

            return result;
        }
    }

    #endregion
}

你可以这样使用它:

string json = ...;

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

dynamic obj = serializer.Deserialize(json, typeof(object));

给定一个JSON字符串:

{
  "Items":[
    { "Name":"Apple", "Price":12.3 },
    { "Name":"Grape", "Price":3.21 }
  ],
  "Date":"21/11/2010"
}

下面的代码将在运行时工作:

dynamic data = serializer.Deserialize(json, typeof(object));

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

如何解析简单的JSON内容与动态& JavaScriptSerializer

请添加System.Web.Extensions的引用,并使用System.Web.Script.Serialization添加此命名空间;在前:

public static void EasyJson()
{
    var jsonText = @"{
        ""some_number"": 108.541,
        ""date_time"": ""2011-04-13T15:34:09Z"",
        ""serial_number"": ""SN1234""
    }";

    var jss = new JavaScriptSerializer();
    var dict = jss.Deserialize<dynamic>(jsonText);

    Console.WriteLine(dict["some_number"]);
    Console.ReadLine();
}

如何解析嵌套和复杂的json与动态和JavaScriptSerializer

请添加System.Web.Extensions的引用,并使用System.Web.Script.Serialization添加此命名空间;在前:

public static void ComplexJson()
{
    var jsonText = @"{
        ""some_number"": 108.541,
        ""date_time"": ""2011-04-13T15:34:09Z"",
        ""serial_number"": ""SN1234"",
        ""more_data"": {
            ""field1"": 1.0,
            ""field2"": ""hello""
        }
    }";

    var jss = new JavaScriptSerializer();
    var dict = jss.Deserialize<dynamic>(jsonText);

    Console.WriteLine(dict["some_number"]);
    Console.WriteLine(dict["more_data"]["field2"]);
    Console.ReadLine();
}

用Newtonsoft创建动态对象。Json真的很棒。

//json is your string containing the JSON value
dynamic data = JsonConvert.DeserializeObject<dynamic>(json);

现在您可以像访问普通对象一样访问数据对象。这是我们当前的JSON对象示例:

{ "ID":123,"Name":"Jack","Numbers":[1, 2, 3] }

这是你在反序列化后访问它的方式:

data.ID //Retrieve the int
data.Name //Retrieve the string
data.Numbers[0] //Retrieve the first element in the array

看看我在CodeProject上写的一篇文章,它准确地回答了这个问题:

使用JSON的动态类型。网

这里有太多的内容需要重新发布,甚至更没有意义,因为那篇文章有一个带有密钥/所需源文件的附件。