我有以下代码:
var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
responsecontent中的输入是JSON,但它没有正确地反序列化为对象。我应该如何正确地反序列化它?
我有以下代码:
var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
responsecontent中的输入是JSON,但它没有正确地反序列化为对象。我应该如何正确地反序列化它?
当前回答
我假设你没有使用Json。净(Newtonsoft。Json NuGet包)。如果是这样的话,你应该试试。
它具有以下特点:
LINQ到JSON JsonSerializer用于快速将.NET对象转换为JSON并再转换回来 Json。NET可以选择生成格式良好、缩进的JSON以供调试或显示 可以将JsonIgnore和JsonProperty等属性添加到类中,以自定义类的序列化方式 能够将JSON转换为XML 支持多种平台:.NET、Silverlight和Compact Framework
请看下面的例子。在本例中,JsonConvert类用于将对象与JSON进行转换。它有两个用于此目的的静态方法。它们是SerializeObject(Object obj)和DeserializeObject<T>(String json):
using Newtonsoft.Json;
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
其他回答
使用这个工具在json中生成一个类:
http://json2csharp.com/
然后使用类来反序列化json。例子:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
string json = @"{
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// james@example.com
引用: https://forums.asp.net/t/1992996.aspx?Nested+Json+Deserialization+to+C+object+and+using+that+object https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
var result = controller.ActioName(objParams);
IDictionary<string, object> data = (IDictionary<string, object>)new System.Web.Routing.RouteValueDictionary(result.Data);
Assert.AreEqual("Table already exists.", data["Message"]);
以下来自msdn站点的内容应该有助于为您正在寻找的内容提供一些本地功能。请注意,这是针对Windows 8指定的。下面列出了该站点中的一个这样的示例。
JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
它利用了Windows.Data.JSON命名空间。
我最终创建了一个简单的类,可以动态地创建类型,实例化它们并将它们水合物化,镜像输入JSON的结构。
你可以在这里找到它:
https://github.com/starnutoditopo/JsonToObject
JsonToObjectConverter.cs
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.Json;
namespace JsonToObject;
/// <summary>Provides functionalities to convert JSON strings in to CLR objects.</summary>
public class JsonToObjectConverter
{
private class Counter
{
private ulong count;
public Counter()
{
this.count = 0;
}
public ulong Next()
{
this.count++;
return this.count;
}
}
private static ulong assemblyGenerationCounter;
private readonly JsonToObjectConverterOptions options;
static JsonToObjectConverter()
{
assemblyGenerationCounter = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonToObjectConverter" /> class, using default options.
/// </summary>
/// <param name="options">The options.</param>
public JsonToObjectConverter()
: this(new JsonToObjectConverterOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonToObjectConverter" /> class, using the specified options.
/// </summary>
/// <param name="options">The options.</param>
public JsonToObjectConverter(JsonToObjectConverterOptions options)
{
this.options = options;
}
/// <summary>Converts a JSON string to an instance of a CLR object.</summary>
/// <param name="jsonString">The json string.</param>
/// <returns>
/// <br />
/// </returns>
public object? ConvertToObject(string jsonString)
{
JsonSerializerOptions opt = new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
};
JsonElement rawResult = JsonSerializer.Deserialize<JsonElement>(jsonString, opt);
object? result = ToStronglyTypedObject(rawResult);
return result;
}
private object? ToStronglyTypedObject(JsonElement? nullableJsonElement)
{
string assemblyNameString;
ulong assemblyId = Interlocked.Increment(ref assemblyGenerationCounter);
try
{
assemblyNameString = string.Format(this.options.RuntimeGeneratedAssemblyNameTemplate, assemblyId.ToString(CultureInfo.InvariantCulture));
}
catch
{
throw new InvalidOperationException($@"Unable to generate assembly name using template '{this.options.RuntimeGeneratedAssemblyNameTemplate}' and id '{assemblyId}'. Please, review the {nameof(JsonToObjectConverterOptions.RuntimeGeneratedAssemblyNameTemplate)} property in the options.");
}
ModuleBuilder moduleBuilder = CreateModuleBuilder(assemblyNameString, this.options.RuntimeGeneratedModuleName);
Counter typeGenerationCounter = new Counter();
var result = ToStronglyTypedObject(nullableJsonElement, moduleBuilder, typeGenerationCounter);
return result;
}
private object? ToStronglyTypedObject(
JsonElement? nullableJsonElement,
ModuleBuilder moduleBuilder,
Counter typeGenerationCounter
)
{
if (nullableJsonElement == null)
{
return null;
}
JsonElement jsonElement = nullableJsonElement.Value;
switch (jsonElement.ValueKind)
{
case JsonValueKind.Undefined:
return null;
case JsonValueKind.String:
return jsonElement.GetString();
case JsonValueKind.False:
return false;
case JsonValueKind.True:
return true;
case JsonValueKind.Null:
return null;
case JsonValueKind.Number:
{
if (jsonElement.TryGetDouble(out var result))
{
return result;
}
}
throw new InvalidOperationException($"Unable to parse {jsonElement} as number.");
case JsonValueKind.Object:
{
ulong typeId = typeGenerationCounter.Next();
string typeName;
try
{
typeName = string.Format(this.options.RuntimeGeneratedTypeNameTemplate, typeId.ToString(CultureInfo.InvariantCulture));
}
catch
{
throw new InvalidOperationException($@"Unable to generate type name using template '{this.options.RuntimeGeneratedTypeNameTemplate}' and id '{typeId}'. Please, review the {nameof(JsonToObjectConverterOptions.RuntimeGeneratedTypeNameTemplate)} property in the options.");
}
TypeBuilder typeBuilder = CreateTypeBuilder(moduleBuilder, typeName);
Dictionary<string, object?> propertyValues = new Dictionary<string, object?>();
foreach (var property in jsonElement.EnumerateObject())
{
string propertyName = property.Name;
object? propertyValue = ToStronglyTypedObject(property.Value, moduleBuilder, typeGenerationCounter);
Type propertyValueType;
if (null == propertyValue)
{
propertyValueType = typeof(object);
}
else
{
propertyValueType = propertyValue.GetType();
}
CreateAutoImplementedProperty(typeBuilder, propertyName, propertyValueType);
propertyValues.Add(propertyName, propertyValue);
}
Type resultType = typeBuilder.CreateType()!;
object result = Activator.CreateInstance(resultType)!;
foreach (var pair in propertyValues)
{
var propertyInfo = resultType.GetProperty(pair.Key)!;
propertyInfo.SetValue(result, pair.Value);
}
return result;
}
case JsonValueKind.Array:
{
List<object?> list = new List<object?>();
foreach (var item in jsonElement.EnumerateArray())
{
object? value = ToStronglyTypedObject(item, moduleBuilder, typeGenerationCounter);
list.Add(value);
}
return list.ToArray();
}
default:
throw new InvalidOperationException($"Value type '{jsonElement.ValueKind}' is not supported");
}
}
private static ModuleBuilder CreateModuleBuilder(
string assemblyNameString,
string moduleName
)
{
// create assembly name
var assemblyName = new AssemblyName(assemblyNameString);
// create the assembly builder
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
// create the module builder
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName);
return moduleBuilder;
}
private static TypeBuilder CreateTypeBuilder(
ModuleBuilder moduleBuilder,
string typeName
)
{
// create the type builder
TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public);
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
return typeBuilder;
}
private static void CreateAutoImplementedProperty(
TypeBuilder builder,
string propertyName,
Type propertyType
)
{
const string PrivateFieldPrefix = "m_";
const string GetterPrefix = "get_";
const string SetterPrefix = "set_";
// Generate the field.
FieldBuilder fieldBuilder = builder.DefineField(
string.Concat(PrivateFieldPrefix, propertyName),
propertyType, FieldAttributes.Private);
// Generate the property
PropertyBuilder propertyBuilder = builder.DefineProperty(
propertyName, PropertyAttributes.HasDefault, propertyType, null);
// Property getter and setter attributes.
MethodAttributes propertyMethodAttributes =
MethodAttributes.Public | MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
// Define the getter method.
MethodBuilder getterMethod = builder.DefineMethod(
string.Concat(GetterPrefix, propertyName),
propertyMethodAttributes, propertyType, Type.EmptyTypes);
// Emit the IL code.
// ldarg.0
// ldfld,_field
// ret
ILGenerator getterILCode = getterMethod.GetILGenerator();
getterILCode.Emit(OpCodes.Ldarg_0);
getterILCode.Emit(OpCodes.Ldfld, fieldBuilder);
getterILCode.Emit(OpCodes.Ret);
// Define the setter method.
MethodBuilder setterMethod = builder.DefineMethod(
string.Concat(SetterPrefix, propertyName),
propertyMethodAttributes, null, new Type[] { propertyType });
// Emit the IL code.
// ldarg.0
// ldarg.1
// stfld,_field
// ret
ILGenerator setterILCode = setterMethod.GetILGenerator();
setterILCode.Emit(OpCodes.Ldarg_0);
setterILCode.Emit(OpCodes.Ldarg_1);
setterILCode.Emit(OpCodes.Stfld, fieldBuilder);
setterILCode.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getterMethod);
propertyBuilder.SetSetMethod(setterMethod);
}
}
JsonToObjectConverterOptions.cs
namespace JsonToObject;
/// <summary>
/// Defines the options to instantiate a <see cref="JsonToObjectConverter" /> object.
/// </summary>
public class JsonToObjectConverterOptions
{
private const string CONSTANTS_RuntimeGeneratedModuleName = $"RuntimeGeneratedModule";
private const string CONSTANTS_RuntimeGeneratedAssemblyNameTemplate = "RuntimeGeneratedAssembly_{0}";
private const string CONSTANTS_RuntimeGeneratedTypeNameTemplate = "RuntimeGeneratedType_{0}";
/// <summary>Gets or sets the name of the runtime-generated module.</summary>
/// <value>The name of the runtime-generated module.</value>
public string RuntimeGeneratedModuleName { get; set; } = CONSTANTS_RuntimeGeneratedModuleName;
/// <summary>Gets or sets the template to use to generate the name of runtime-generated assemblies.</summary>
/// <value>The template to use to generate the name of runtime-generated assemblies.</value>
/// <remarks>Should contain a "{0}" placeholder.</remarks>
public string RuntimeGeneratedAssemblyNameTemplate { get; set; } = CONSTANTS_RuntimeGeneratedAssemblyNameTemplate;
/// <summary>Gets or sets the template to use to generate the name of runtime-generated types.</summary>
/// <value>The template to use to generate the name of runtime-generated types.</value>
/// <remarks>Should contain a "{0}" placeholder.</remarks>
public string RuntimeGeneratedTypeNameTemplate { get; set; } = CONSTANTS_RuntimeGeneratedTypeNameTemplate;
}
另一个本地解决方案是JavaScriptSerializer,它不需要任何第三方库,只需要对System.Web.Extensions的引用。这不是一个新功能,而是一个自3.5以来非常不为人知的内置功能。
using System.Web.Script.Serialization;
..
JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());
和背部
MyObject o = serializer.Deserialize<MyObject>(objectString)