.NET Core 3.1 API returns empty JSON objects – Solved

I faced one strange issue during the migration process of .NET Core 2.2 to .NET Core 3.1.

All the steps as per Microsoft was done and the API runs successfully in .NET Core 3.1. I feel very excited, but when I tested and looked at the output then I was shocked.

There were neither compile-time errors nor run time errors and the output was just an empty JSON object as shown below.

[
  [
    [
      []
    ],
    [
      []
    ]
  ]
]

Below is the sample code snippet.

        [HttpPost]
        [Route("TestAPI")]
        public IActionResult TestAPI()
        {
            string jsonData = @"[{	'Country': 'India',    'City': 'New Delhi'}]";
            return Ok(JArray.Parse(jsonData));
        }

After spending some time on Google I found a solution and applied the same and yes it works as expected.

I changed the return statement to below to resolve this issue-

return  Content(jsonData.ToString(), "application/json", Encoding.UTF8);

Final code snippet –

        [HttpPost]
        [Route("TestAPI")]
        public IActionResult TestAPI()
        {
            string jsonData = @"[{	'Country': 'India',    'City': 'New Delhi'}]";
            return Content(jsonData.ToString(), "application/json", Encoding.UTF8);
        }

Below is the output which was expected –

[{	'Country': 'India',    'City': 'New Delhi'}]

This was one of the code level change while migrating .NET Core 2.2 based project to .NET Core 3.1

Leave a Comment

RSS
YouTube
YouTube
Instagram