Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft.Json.JsonReaderException: Could not convert string to integer 2

i am currently at integration testing phase in my project and i ran into an error while trying to test an endpoint to see if my database returns some tasks. my domain object looks like this:

public class Task
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }

        [Column(TypeName = "decimal(18,2)")] 
        public decimal? InitialPrice { get; set; }
    }

My basic test code for an endpoint

[Fact]
        public async Task Should_return_All_Tasks_with_ok_statusCode()
        {
            client.SetFakeBearerToken((object) token);
            
            var response = await client.GetAsync("/api/v1/tasks");

            response.StatusCode.Should().Be(HttpStatusCode.OK);
            var json = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<Task>>(json);
            data.Count.Should().BeGreaterThan(0);
        }

When i run the test i get the error

Newtonsoft.Json.JsonReaderException: Could not convert string to integer: 64fa643f-2d35-46e7-b3f8-31fa673d719b. Path '[0].id', line 1, position 45.

I have also tried using the ReadAsAsync<List>() method from the webapi.client package and i still get the same error.

an api call to the endpoint im trying to test would give:

[
  {
    "id": "64fa643f-2d35-46e7-b3f8-31fa673d719b",
    "title": "Garden Trimming in Lagos Ajah",
    "description": "Please my garden needs trimmin, Im in lagos",
    "initialPrice": 20.3
  }
]

I would appreciate the help


1 Answers

You named your Task class the same as the System.Threading.Tasks.Task object in the .Net framework. The System.Threading.Tasks.Task has an int Id property. Your code to deserialize is actually trying to deserialize your JSON into the System.Threading.Tasks.Task object.

To fix this you need to either rename your Task class, which I would recommend, or specify the full name to your Task object, including the namespace, in your line of code that's calling JsonConvert.DeserializeObject.

like image 185
quaabaam Avatar answered Aug 16 '26 21:08

quaabaam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!