I would appreciate your help. I have been struggling with this for way too long.
I could easily get around this by creating two separate model classes with a duplicate list of properties, but I'd like to learn how to achieve this with the base class. So, an IntSensor
and ExtSensor
are both a Sensor
. From another class I parse a json file with all of the data and that works great. But, trying to call a method that returns a List<Sensor>
baseclass and trying to cast it as either subclass is killing me. What am I doing wrong... or is there a better way? Thank you!
PS: this may look like a duplicate question, but I tried the other solutions and they are marked in the `Repository class' as "//seen on other StackOverflow Posts -- fails" in the code.
//Model classes
public class Device
{
public string IP { get; set; }
public string Name { get; set; }
public IList<IntSensor> InternalSensors { get; set; }
public IList<ExtSensor> ExternalSensors { get; set; }
}
public class Sensor
{
public string Name { get; set; }
public string ActualTemp { get; set; }
public string HighTemp { get; set; }
public string LowTemp { get; set; }
}
public class IntSensor : Sensor {}
public class ExtSensor : Sensor {}
//Business Class -- parsing json
public class ParseJsonData
{
public static RoomAlertModel GetRoomAlertModel(JObject jsonTree)
{
RoomAlertModel model = new RoomAlertModel();
model.IP = jsonTree["ip"].ToString();
model.Name = jsonTree["name"].ToString();
return model;
}
public static List<Sensor> GetSensors(JToken jToken)
{
var sensors = new List<Sensor>();
try
{
foreach (var item in jToken)
{
var s = new Sensor();
s.Label = item["lab"].ToString();
s.ActualTemp = item["tf"] != null ? item["tf"].ToString() : "";
s.HighTemp = item["hf"] != null ? item["hf"].ToString() : "";
s.LowTemp = item["lf"] != null ? item["lf"].ToString() : "";
sensors.Add(s);
}
}
catch (Exception)
{
}
return sensors;
}
}
//Repository
public class RoomAlertRepository
{
internal RoomAlertModel Retreive()
{
var filePath = HostingEnvironment.MapPath(@"~/App_Data/RoomAlertsData.json");
var json = File.ReadAllText(filePath);
JObject jsonTree = JObject.Parse(json);
var internalSensorTree = jsonTree["internal_sen"];
var externalSensorTree = jsonTree["sensor"];
var model = ParseJsonData.GetRoomAlertModel(jsonTree);
var baseList = ParseJsonData.GetSensors(internalSensorTree);
//seen on other StackOverflow Posts -- fails
var iSensorsTry1 = baseList.Cast<IntSensor>();
//seen on other StackOverflow Posts -- fails
var iSensorsTry2 = baseList.ConvertAll(instance => (IntSensor)instance);
//seen on other StackOverflow Posts -- fails
var iSensorsTry3 = baseList.OfType<IntSensor>();
model.InternalSensor = iSensorsTry1.ToList();
return model;
}
}