Upgrading .Net 6.0 to .Net 8.0 – JsonConvert.DeserializeObject

Posted: February 13, 2024  |  Categories: Azure

I describe an issue I encounter with JsonConvert.DeserializeObject(String) method on upgrading from .Net 6.0 to .Net 8.0. In the first place, testing of an Azure function after upgrading from .NET 6.0 to .Net 8.0 bought this to my attention.

The issue

Firstly the .Net 6.0 version of my function was returning.

{
    "UserBranches": [
        {}
    ],
    "SiteCode": "NZ",
    "SupplierCode": "BIDEXC",
    "Name": "EXCLUSIVE BRANDS BIDFOOD LTD",
    "LastName": "Bruce",
    "FirstName": "Clinton",
    "LoginID": "********",
    "Email": "*********"
}

Whereas the .Net 8.0 version loses all the values.

{
    "UserBranches": [
        []
    ],
    "SiteCode": [],
    "SupplierCode": [],
    "Name": [],
    "LastName": [],
    "FirstName": [],
    "LoginID": [],
    "Email": []
}

Investigation

Local debugging shows that the following line of code was at fault.

? (ActionResult)new OkObjectResult(JsonConvert.DeserializeObject(jsonResult.ToString()))
: new BadRequestObjectResult("login id is required and max length is 254.");

If I replace this line of code with this fragment

  return code != null
      ? (ActionResult)new OkObjectResult(jsonResult.ToString())
      : new BadRequestObjectResult("login id is required and max length is 254.");
}

I get the same response as I get from .Net 6.0, albeit as a text object instead of a JSON object.

We are using this version of the Newtonsoft library.

#region Assembly Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
// C:\Users\Mark.Brimble\.nuget\packages\newtonsoft.json\11.0.2\lib\netstandard2.0\Newtonsoft.Json.dll
// Decompiled with ICSharpCode.Decompiler 8.1.1.7464


Secondly, the string is valid JSON and is the same in .NET 6.0 version. Thirdly checking the compatibility of the Json.NET library with the .Net 8.0 framework did not reveal any know issues. Fourthly there is no error message.

Workaround

Create a class called Users to represent the JSON and deserialize using this class. Replace the Newsoft library with System.Txt.Json

            return code != null
                ? (ActionResult)new OkObjectResult(JsonSerializer.Deserialize<Users>(jsonResult.ToString()))
                : new BadRequestObjectResult("login id is required and max length is 254.");

Summary

I have shown that the JsonConvert.DeserializeObject(String) method in an .Net 8.0 Azure function does not behave in the same way as a .Net 6.0 version in my hands. Does anyone know whether this is a defect? If this is true, then I think this has the potential to break a lot of code.

turbo360

Back to Top