繁体   English   中英

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

[英]Deserialize JSON string into class with reflection

我正在尝试将 JSON 字符串反序列化为自定义类。 我必须使用反射。 我有一个序列化的字典,发送到 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”类。 这是我读取 jsonString 的 HttpPut 方法:

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

这会产生错误:

Newtonsoft.Json.Linq.JObject' 类型的对象不能转换为'Person' 类型;

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

Newtonsoft.Json.JsonSerializationException:无法将 JSON 对象填充到类型“Person”上。 路径“personName”,第 1 行....

所以基本上,您如何获取一个 JSON 字符串,将其转换为一个类(在我的例子中为“Person”类),并通过反射将其设置为 customObject 的 Person 字段?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM