[英]How do I deserialize a generic complex object from json?
I'm writing a generic method that takes a Dictionary<string, object>
and uses reflection to hydrate an object of type T
: 我正在编写一个通用方法,该方法采用
Dictionary<string, object>
并使用反射来水合T
类型的对象:
private T HydrateRequestObject<T>(Dictionary<string, object> requestParameters)
{
dynamic requestObject = Activator.CreateInstance<T>();
PropertyInfo[] requestProperties = typeof(T).GetProperties();
foreach (PropertyInfo prop in requestProperties)
{
//Fails with complex json
prop.SetValue(requestObject, requestParameters[prop.Name]);
}
return requestObject;
}
Currently, this handles simple parameters and properties such as: 当前,它处理简单的参数和属性,例如:
"params" : {
"CompanyID" : 50
}
But I also need to support complex parameters such as: 但是我还需要支持复杂的参数,例如:
"params": {
"Resource": {
"FirstName": "test",
"LastName": "test",
"MiddleInitial": null,
"Suffix": null,
"Phone1": "test",
"Phone2": null,
"Phone3": null,
"Email": "test",
"AddressID": 47
},
"ResourceSaveType": 0
}
Currently I get an ArgumentException: "Object of type Newtonsoft.Json.Linq.JObject
cannot be converted to type Resource
." 当前,我收到一个ArgumentException:“
Newtonsoft.Json.Linq.JObject
类型的对象无法转换为Resource
类型。” Is there a way to traverse the json to set all the properties in the object? 有没有一种遍历json来设置对象中所有属性的方法? Or am I approaching this in the wrong way?
还是我以错误的方式处理此问题?
The thing is no-one can know for sure what type should object resolve to - you have to specify it explicitly. 没人能确定对象应该解析为哪种类型,这是必须要明确指定的。 Imagine for example you have also object of type Person in Dictionary (with properties FirstName, LastName) - how can json library know that Resource should be of Resource class ?
想象一下,例如,您在Dictionary中还具有Person类型的对象(具有属性FirstName,LastName)-json库如何知道Resource应该属于Resource类?
Explicitly specified type example: 明确指定的类型示例:
using System.Collections.Generic;
namespace ConsoleApplication1 {
public class Resource {
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program {
static void Main(string[] args) {
var foo = @"{
""$type"":""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",
""Resource"":{""$type"":""ConsoleApplication1.Resource, ConsoleApplication1"",
""FirstName"":""rrr"",
""LastName"":null}}";
var bar = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(
foo,
new Newtonsoft.Json.JsonSerializerSettings {
TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects,
});
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.