dynamic object null reference exception

Neo Yu 6 Reputation points
2021-06-09T14:04:01.137+00:00

Hello,

Windows 10 + VS 2019 community + .Net 5.0

I was working on a little tool, which basically retrieve info from Web using API. I'm using Json to convert results as a dynamic object, then add the results to my list one by one. Everything works perfectly, I can see values there in item during debug, but it returns a null reference exception instead. Can you please help check if anything is wrong? Apology if the question is too simple as I'm new to C#. Thank you.

dynamic proList = JsonConvert.DeserializeObject(readResult);
foreach (var item in proList)
{
allPrograms.Add(new SWTProgram { ProgramName = item["ProgramName"], ProgramID = item["ProgramID"] });

                        }  

103934-image.png

103858-image.png

Developer technologies .NET .NET Runtime
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2021-06-09T20:53:23.603+00:00

    There are several issues with the code and design. Use await not .Results(). Your code blocks the main thread which async/await is designed to fix.

    string readResult = await result.Content.ReadAsStringAsync()
    

    The dynamic type is not used correctly. Dynamic is designed for interfacing with dynamically typed languages. Use a strong type since you are interfacing with C#. DeserializeObject<T> takes a generic <T> so just pass the actual type. Reference Docs

    Use Visual Studio to generate the strong type from the JSON stream. Copy the JSON. From the Edit menu select "Paste Special". Then click "Paste JSON as Classes". Visual Studio will create the classes for you.

    3 people found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.