I'm trying to deserialize a JSON string into a custom class. I have to use reflection. I have a dictionary that I serialize, send over to an HttpPut method, deserialize the JSON string, and read the dictionary fields. Here's what I have so far:
I'm putting values into the Dictionary like this:
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);
I'm using JSON to serialize it like this:
string jsonString = JsonConvert.SerializeObject(valuesToUpdate);
I then take the jsonString and send it over to a REST API PUT method. The PUT method updates various variables on a custom object based on the Key values in the dictionary using reflection (In this example I'm updating customObject.Person and customObject.Length).
The PUT call deserializes the jsonString like this:
Dictionary<string, object> newFields = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
I iterate through newFields and want to use reflection to update customObject's "Person" class. This is my HttpPut method that reads the 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);
}
}
}
This generates the error:
Object of type Newtonsoft.Json.Linq.JObject' cannot be converted to type 'Person';
I've also tried using JSON's PopulateObject method but it returned this error:
Newtonsoft.Json.JsonSerializationException: Cannot populate JSON object onto type 'Person'. Path 'personName', line 1....
So basically, how can you go about taking a JSON string, converting it to a class (in my case the 'Person' class), and setting it to customObject's Person field with reflection?