In My code, I am trying to receive an API containing a JSON body containing data, I have designed a DataInfo Model class and used the [FromBody] function to translate the data.
My issue is that the data being pulled which I have formatted to be ints and doubles, is being pulled as a series of 0s
My Data Info Model Class:
public class DataInfo
{
[JsonProperty("ID")]
public int JId { get; set; }
[JsonProperty("Temp")]
public double JTemperature { get; set; }
[JsonProperty("Humidity")]
public double JHumidity { get; set; }
[JsonProperty("WindSpeed")]
public double JWindSpd { get; set; }
[JsonProperty("SoilMoisture")]
public double JSM { get; set; }
}
} My Api Controller: [HttpPatch("update")]
public async Task<ActionResult<Device>> Update([FromBody] DataInfo data)
{
var dev = await _dbContext.Device.Where(x => x.Id == data.JId).FirstOrDefaultAsync();
if (dev == null)
{
return BadRequest("no device found");
}
dev.Humidity = data.JHumidity;
dev.Temp = data.JTemperature;
dev.WindSpeed = data.JWindSpd;
dev.SoilMoisture = data.JSM;
dev.DateTime = DateTime.Now;
_dbContext.SaveChanges();
return Ok(dev);
}
My JsonBody: {
"ID":"1",
"Temp":"37",
"Humidity":"42",
"WindSpeed":"12",
"SoilMoisture":"14"
} I also Used this JSON body and got the same result:
{ "data":{
"ID":"1",
"Temp":"37",
"Humidity":"42",
"WindSpeed":"12",
"SoilMoisture":"14"
}
}
When I run the API call in postman, I receive a 400 error with the text that correlates to an invalid Device ID, when I had it send the Device ID and other data points within the class, all were returned as 0s.
The API call is going to the correct controller, however the JSON data seems only to be exsisting as 0s even though I assign it with the JsonPropertyName or JsonProperty assignment in the model class.
I found the issue to be in My Using inputs. I was including Newtonsoft which was conflicting with system.
using BlazorApp1.Data;
using BlazorApp1.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
//using Newtonsoft.Json;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;