Home > Software engineering >  Cannot convert value to NodaTime.Instant
Cannot convert value to NodaTime.Instant

Time:08-18

I had this problem trying to pass an instant date in the body of a post http call.

My API model:

public class ConfortPlantRequestDTO
    {
        public Instant instantStartDate { get; set; }
        public Instant instantEndDate { get; set; }
        public List<string> plants { get; set; } = new List<string>();
    }

This is my Controller:

[HttpPost]
[Route("GetComfortPlant")]
public async Task<ActionResult> GetComfortPlant([FromBody] ConfortPlantRequestDTO requestData)
{
  try
  {
      return Ok(await _confortPlantGraphicsService.getComfortPlantAsync(requestData));
  }
  catch (Exception ex)
  {
      CoreLogger.Error($"Exception: {ex}");
      return BadRequest(ex.Message);
  }
}

JSON Body:

{
  "instantStartDate": "2020-10-01T00:00:00.00Z",
  "instantEndDate": "2023-05-15T00:00:00.00Z",
  "plants": [
    1,
    2,
    3,
    4,
    5,
    10,
    397,
    22,
    404,
    45
  ]
}

Error

{
  "errors": {
    "instantEndDate": [
      "Error converting value 15/05/2023 00:00:00 to type 'NodaTime.Instant'. Path 'instantEndDate', line 3, position 45."
    ],
    "instantStartDate": [
      "Error converting value 01/10/2020 00:00:00 to type 'NodaTime.Instant'. Path 'instantStartDate', line 2, position 47."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-28675fabe9fde94c8749f873eb69aac0-01b932d00e8ed149-00"
}

I don't understand why it can't convert the date since doing it with a get passing the parameters in the url, it works

CodePudding user response:

you have to fix your DTO class

using Newtonsoft.Json;

var result=JsonConvert.DeserializeObject<ConfortPlantRequestDTO>(json);


public class ConfortPlantRequestDTO
{
    public DateTime instantStartDate { get; set; }
    public DateTime instantEndDate { get; set; }
    public List<string> plants { get; set; } = new List<string>();
}

CodePudding user response:

I solved it by adding 7 zeros to the date that is passed in the json file.

Solution:

Change the two parameters representing the date from:

"instantStartDate": "2020-10-01T00:00:00.00Z",
"instantEndDate": "2023-05-15T00:00:00.00Z",

To:

"instantStartDate": "2020-10-01T00:00:00.000000000Z",
"instantEndDate": "2023-05-15T00:00:00.000000000Z",

I found the solution on :https://nodatime.org/3.0.x/api/NodaTime.Instant.html

  • Related