使用反射将 JSON 字符串反序列化为 class

Deserialize JSON string into class with reflection

我正在尝试将 JSON 字符串反序列化为自定义 class。我必须使用反射。我有一个我序列化的字典,发送到 HttpPut 方法,反序列化 JSON 字符串,然后读取字典字段。这是我目前所拥有的:

我像这样将值放入字典中:

Dictionary<string, object> valuesToUpdate = new Dictionary<string, object>();
Person p = new Person();
p.personName = "OrigName";
p.age = "25";
p.isAlive = true;
valuesToUpdate.Add("Person", p);
valuesToUpdate.Add("Length", 64.0);

我正在使用 JSON 像这样序列化它:

string jsonString = JsonConvert.SerializeObject(valuesToUpdate);

然后我获取 jsonString 并将其发送到 REST API PUT 方法。 PUT 方法使用反射根据字典中的键值更新自定义对象上的各种变量(在此示例中,我正在更新 customObject.Person 和 customObject.Length)。

PUT 调用反序列化 jsonString,如下所示:

Dictionary<string, object> newFields = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

我遍历 newFields 并想使用反射来更新 customObject 的 "Person" class。这是我的 HttpPut 方法,它读取 jsonString:

[HttpPut("/test/stuff")]
public string PutContact([FromBody]dynamic jsonString)
{
    Dictionary<string, object> newFields = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
    foreach (var field in newFields)
    {
        Console.WriteLine("\nField key: " + field.Key);
        Console.WriteLine("Field value: " + field.Value + "\n");

        PropertyInfo propInfo = typeof(Contact).GetProperty(field.Key);
        Type propertyType = propInfo.PropertyType;
        var value = propInfo.GetValue(contactToUpdate, null);

        if (propertyType.IsClass)
        {
            propInfo.SetValue(contactToUpdate, field.Value, null);
        }
    }
}

这会产生错误:

Object of type Newtonsoft.Json.Linq.JObject' cannot be converted to type 'Person';

我也尝试过使用 JSON 的 PopulateObject 方法,但它返回了这个错误:

Newtonsoft.Json.JsonSerializationException: Cannot populate JSON object onto type 'Person'. Path 'personName', line 1....

所以基本上,您如何获取 JSON 字符串,将其转换为 class(在我的例子中是 'Person' class),然后设置它通过反射传递到 customObject 的 Person 字段?

if (propertyType.IsClass)
{
    propInfo.SetValue(contactToUpdate, ((JObject)field.Value).ToObject(propertyType), null);
}