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

标签 c# json class serialization http-put

我正在尝试将 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);
        }
    }
}

这会产生错误:

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 字符串,将其转换为类(在我的例子中为“Person”类),并通过反射将其设置为 customObject 的 Person 字段?

最佳答案

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

关于c# - 使用反射将 JSON 字符串反序列化为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36728307/

相关文章:

c# - 将新列添加到 GridView DevExpress

c# - 在 Emgu Cv 中写入视频时出错

iphone - NSJSONSerialization 出错 - JSON 写入中的类型无效(菜单)

java - Java 如何决定何时导入?

c# - 在主屏幕锁定鼠标

c# - 以编程方式获取 Google 中索引页面的数量?

json - JQ:如何使用 jq 选择的数据创建 JSON 对象?

javascript - 有没有可能让 JSON.stringify 保留函数?

c++在分配对象私有(private)时

JavaScript:尝试使用由于某种原因无法运行的类函数