Recently, I was involved in one of the migration projects. I had to migrate the existing ASP.NET Core 2.2-based project to .NET Core 3.1.
I faced a few challenges and errors during the migration. However, one of the errors related to JSON took a lot of my effort. So I thought to post it here.
Error message – Object serialized to Object. JArray instance expected
Below is the code snippet –
[HttpPost]
[Route("GetData")]
public IActionResult GetData([FromBody] object json)
{
try
{
var jsonData = JSONModifier(JArray.FromObject(json));
return Content(jsonData.ToString(), "application/json", Encoding.UTF8);
}
catch (Exception ex)
{
throw;
}
}
public JArray JSONModifier(JArray inputJson)
{
//Do some tasks here
return inputJson;
}
The above code was working fine in ASP.NET Core 2.2. Once I migrated this application to .NET Core 3.1 then the above code started throwing the below error.
How to resolve this error – JArray instance expected
I started exploring the internet and tried one suggestion and it worked for me.
We need to make a small change that is mentioned below. Instead, JArray.FromObject
we will use JArray.Parse
and this way we will resolve this error.
var jsonData = JSONModifier(JArray.Parse(json.ToString()));
I hope this article is useful to you.
Please read the migration article – How to Migrate from ASP.NET Core 2.2 project to .NET Core 3.1?