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

时间:2014-03-20 14:17:20

标签: c# .net json reflection

我正在编写一个通用方法,它采用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来设置对象中的所有属性?或者我是以错误的方式接近这个?

1 个答案:

答案 0 :(得分:0)

事情是没有人可以确定应该对象解决的类型 - 你必须明确指定它。想象一下,例如你在Dictionary中也有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,
      });

    }
  }
}