I am supposed to create a controller for the format below. I made the following data model and controller, but I am getting an error "Objects reference is not set to an instance of an object"
I am not very familiar with the framework and most sure what's wrong with the current implimentation
{
"MacAddress": "30:a3:d5:a6:e4:b3",
"TotalNodes": 1,
"Report": [{
"Status": [{
"ID": 3,
"Val": 0,
"RSSI": {
"Hop1": -80,
"Hop2": -10
},
"Route": {
"Id1": 3,
"Id2": 9
}
}]
}]
}
namespace Data.Models
{
public class SensorsData
{
public string MacAddress { get; set; }
public int TotalNodes { get; set; }
public List<SensorReport> Report{ get; set; }
public class SensorReport
{
public List<Status> Status { get; set; }
}
public class Status
{
public int ID { get; set; }
public string Val { get; set; }
public Nullable<int> HealthVal { get; set; }
public List<sensorsRSSI> RSSI;
public List<sensorsRoute> Route;
}
public class sensorsRSSI
{
public Nullable<int> Hop1 { get; set; }
public Nullable<int> Hop2 { get; set; }
}
public class sensorsRoute
{
public Nullable<int> Id1 { get; set; }
public Nullable<int> Id2 { get; set; }
}
public SensorsHealthData()
{
}
}
}
and the controller looks like this
public IHttpActionResult Post(Data.Models.SensorsData sensorHealthData)
{
try
{
using (GSEntities dbContext = new GSEntities())
{
var device= dbContext.devices.Where(c => c.MacAddress == SensorsData.HubMacAddress).FirstOrDefault();
foreach (SensorReport sensorReport in sensorData.HealthReport)
{
foreach (Status status in sensorReport.Status)
{
SensorsReport sensorReport = GSContext.SensorsReport.Add(new SensorsReport
{
Id = device.Id ,
TotalNodes = sensorData.TotalNodes,
ID = status.ID,
Val= status.Val,
Hop1 = status.RSSI.Hop1,
Hop2 = status.RSSI.Hop2,
Id1 = status.Route.Id1,
Id2 = status.Route.Id2
});
}
}
CodePudding user response:
Based on your model, the fault is the sensorsRSSI
definition in the model class. It is not a list. It must be an object Also sensorsRoute
must be an object.
Suggestion: If you are not similar to the framework or language you can use conversion tools like this for converting JSON to C# model classes.
public class SensorData
{
public string MacAddress { get; set; }
public int TotalNodes { get; set; }
public List<Report> Report { get; set; }
}
public class Report
{
public List<Status> Status { get; set; }
}
public class sensorsRoute
{
public Nullable<int> Id1 { get; set; }
public Nullable<int> Id2 { get; set; }
}
public class sensorsRSSI
{
public Nullable<int> Hop1 { get; set; }
public Nullable<int> Hop2 { get; set; }
}
public class Status
{
public int ID { get; set; }
public int Val { get; set; }
public Nullable<int> HealthVal { get; set; }
// Here is the fault
// this property is not a list just a straight object
public sensorsRSSI RSSI { get; set; }
// And also this property must be an object.
public sensorsRoute Route { get; set; }
}