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


当前回答

我来这里是为了找到。net Core的答案,没有任何第三方或其他参考。如果您将ExpandoObject与标准JsonSerializer类一起使用,那么它工作得很好。下面是一个对我有用的例子:

using System.Text.Json;
using System.Dynamic;

dynamic json = JsonSerializer.Deserialize<ExpandoObject>(jsonText);
Console.WriteLine(json.name);

这段代码输出一个name属性的字符串值,该属性存在于传递给Deserialize方法的JSON文本中。瞧——没有额外的库,什么都没有。只是。net核心。

编辑:有嵌套元素的json的几个级别可能会有问题。适用于单层平面对象。

其他回答

你可以使用System.Web.Helpers.Json——它的Decode方法返回一个动态对象,你可以随意遍历它。

它包含在System.Web.Helpers程序集中(。NET 4.0)。

var dynamicObject = Json.Decode(jsonString);

如果你喜欢依赖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模型。 我的模型是这样的,但它可以改变。

{
    "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" }
...

我在我的代码中使用这样的代码,它工作得很好

using System.Web.Script.Serialization;
JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);

试试这个:

  var units = new { Name = "Phone", Color= "White" };
    var jsonResponse = JsonConvert.DeserializeAnonymousType(json, units);