如何从json反序列化通用复杂对象



我正在编写一个通用方法,该方法采用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;
}

目前,它处理简单的参数和属性,如:

"params" : {
    "CompanyID" : 50
}

但我也需要支持复杂的参数,如:

"params": {
    "Resource": {
      "FirstName": "test",
      "LastName": "test",
      "MiddleInitial": null,
      "Suffix": null,
      "Phone1": "test",
      "Phone2": null,
      "Phone3": null,
      "Email": "test",
      "AddressID": 47
    },
    "ResourceSaveType": 0
}

目前我得到一个ArgumentException:"类型Newtonsoft.Json.Linq.JObject的对象不能转换为类型Resource"是否有一种方法来遍历json设置对象中的所有属性?还是我的思路不对?

问题是没有人能确切地知道对象应该解析成什么类型——你必须明确地指定它。想象一下,例如你在字典中也有Person类型的对象(具有属性FirstName, LastName) - json库如何知道Resource应该属于Resource类?

明确指定的类型示例:

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

相关内容

  • 没有找到相关文章

最新更新