Reputation: 463
On my home automation system, to create a plugin with documentation I must use class with summary.
My plugin talk to my xiaomi gateway to get informations about sensors. So there are different type of sensor like "sensor_ht", "magnet" or "motion".
For each sensor, there are common proprieties and a data part that is different. I get status of each sensor in jon.
For example :
{"cmd":"report","model":"magnet","sid":"","short_id":40805,"data":"
{\"status\":\"close\"}"}
{"cmd":"report","model":"sensor_ht","sid":"","short_id":40805,"data":"
{\"voltage\":\"3000\",\"temperature\":\"2367\",\"humidity,\":\"5285\"}"}
So I create many class like this, each sensor is in a single file.
sensor_ht.cs :
public class sensor_ht
{
public string model { get; set; } = "sensor_ht";
public string sid { get; set; }
public string battery_type { get; set; } = "CR2032";
public int battery { get; set; }
public sensor_ht.Report report { get; set; }
}
public class Report
{
public int voltage { get; set; }
public string temperature { get; set; }
public string humidity { get; set; }
}
magnet.cs :
public class magnet
{
public string model { get; set; } = "sensor_ht";
public string sid { get; set; }
public string battery_type { get; set; } = "CR2032";
public int battery { get; set; }
public magnet.Report report { get; set; }
}
public class Report
{
public int voltage { get; set; }
public string status { get; set; }
}
And this is my report class :
public class Report
{
public string cmd { get; set; }
public string model { get; set; }
public string sid { get; set; }
public int short_id { get; set; }
public string token { get; set; }
public string data { get; set; }
}
After deserialize the report, I initialize the instance with :
dynamic d = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("XiaomiSmartHome.Equipement." + read.model);
But to create the data part I deserialize the data of the report with :
dynamic data2 = JsonConvert.DeserializeObject<dynamic>(read.data);
I want this data to be the right Report class. I tried :
d.report = data2;
But it sais that it's impossible to convert Newtonsoft.Json.Linq.JObject to XiaomiSmartHome.Equipement.Report
So my way to handle this is right ? And how to deserialize the data part to the right report ?
Thank !
Upvotes: 0
Views: 263
Reputation: 463
Ok I finally found the answer, I use :
var messageType = Type.GetType(deserialized.MessageType);
var message = JsonConvert.DeserializeObject(
Convert.ToString(deserialized.Message), messageType);
Upvotes: 2