skip to Main Content

I have to parse an deserialize all the values from the following JSON file:

But I’m getting errors from the compiler.

[
    {
        "CompanyInfo": {  
            "Company": "AdventureWorks",
            "Id": "AW01"
        },
        "ReportsToGenerate": 
        [
            {
                "Type_Report": "Type A Report",
                "Report_Title": "Human Resources Report",
                "Report_Data": 
                [               
                   {
                      "BusinessEntityID":168,
                      "FirstName":"Garrett",
                      "MiddleName":"R",                   
                      "Rate":9.5000
                   },
                   {
                      "BusinessEntityID":278,
                      "FirstName":"Garrett",
                      "MiddleName":"R",
                      "Rate":23.0769
                   }
                ]   
            },
            {
                "Type_Report": "Type B Report",
                "Report_Title": "Sales Report",
                "Report_Data": 
                [
                       {
                          "BusinessEntityID":282,
                          "FirstName":"José",
                          "MiddleName":"Edvaldo",                         
                          "DueDate":"2011-06-12T00:00:00"
                       },
                       {
                          "BusinessEntityID":282,
                          "FirstName":"José",
                          "MiddleName":"Edvaldo",                         
                          "DueDate":"2011-06-12T00:00:00"
                       }
                ]
            },          
        ]
    }
]

I’ve been trying with this code, But I cannot access the Report_Data node values:

public class Report
    {
        public string Type_Report {  get; set; }
        public string Report_Title {  get; set; }
        public List<Report_Data> Report_Data { get; set; }       
    }
public class Report
    {
        public string Type_Report {  get; set; }
        public string Report_Title {  get; set; }
        public List<Report_Data> Report_Data { get; set; }       
    }
public class Report_Data
    {
        public List<TypeAStructure> ReportData_TypeAStructure { get; set; }
        public List<TypeBStructure> ReportData_TypeBStructure { get; set; }
        public List<TypeCStructure> ReportData_TypeCStructure { get; set; }
    }
public class TypeAStructure
    {        
        public int BusinessEntityID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string JobTitle { get; set; }
        public string OrganizationLevel { get; set; }
        public string BirthDate { get; set; }
        public string Gender { get; set; }
        public string MaritalStatus { get; set; }
        public int SickLeaveHours { get; set; }
        public string HireDate { get; set; }
        public string DepartmentName { get; set; }
        public string GroupName { get; set; }
        public string ShiftName { get; set; }
        public double Rate { get; set; }
    }
try
{
    jsonContent = await streamReader.ReadToEndAsync();
    List<Root> root = JsonConvert.DeserializeObject<List<Root>>(jsonContent);
    string sequenceValue = new string(nameFile.Where(char.IsDigit).ToArray());

    foreach (var rootItem in root)
    {
        var companyName = rootItem.CompanyInfo.Company;
        var companyId = rootItem.CompanyInfo.Id;

        foreach (var report in rootItem.ReportsToGenerate)
        {
            await Console.Out.WriteLineAsync(   "hey");
            
            foreach (var listA in report.Report_Data)
            {
                await Console.Out.WriteLineAsync(   "Hey2");
            }
        }
    }
}
catch (System.Text.Json.JsonException ex)
{
    log.LogError(ex, $"There was a deserialization issue with {nameFile}");
}
catch (Exception ex)
{
    log.LogError(ex, $"There was a general exception issue with {nameFile}");
}

I was trying with different llops and structures but I cannot access to the information, I am receiving a System Null Reference Exception and I cannot continue with my application.

Each time that I need to access to the content I receive the same error and I really need to get the values from this Node according with the type of report.

I am working With Newtonsoft Library in my Solution.

How can I deserialize and get the values from the ReportData Node in C#, without changing the source file structure?

2

Answers


  1. I’m not 100% percent sure what you are needed to do in your code, but I have needed to do something similar myself. I will share the code I use to parse a List of JSON objects I get from a queue. Hopefully this helps.

    I’m using Newtonsoft.Json.Linq to do this.

    Here a sample JSON object:

    {
      "$id": "1",
      "MessageType": 1,
      "Answers": [
        {
          "$id": "2",
          "Id": 0,
          "Answer": "2",
          "QuestionId": 1,
          "SectionId": 1
        },
        {
          "$id": "3",
          "Id": 0,
          "Answer": "2",
          "QuestionId": 2,
          "SectionId": 1,
        }    
      ],
      "Totals": [
        {
          "$id": "22",
          "Id": 0,
          "SectionId": 1,
          "Total": 9
        },
        {
          "$id": "23",
          "Id": 0,
          "SectionId": 2,
          "Total": 17
        }
      ]
    }
    

    Below is the code that parses each object:

    foreach (var message in evnt.Records)
    {
        var stringMessageBody = message.Body;
        JObject jsonMessageBody = JObject.Parse(stringMessageBody);
    
        try
        {
            var print = ((JArray)jsonMessageBody["Answers"]).ToString();
            if (print != "[]")
            {
                var messageType = (JValue)jsonMessageBody["MessageType"];
                type = (string)messageType;
    
                switch ((int)messageType)
                {
                    case (int)MessageType.Standard:
                        // Pull the Answers out of the new JObject
                        var answers = (JArray)jsonMessageBody["Answers"];
    
                        // Send the answers to be processed
                        await ProcessAnswersAsync(answers);
                        break;
                    case (int)MessageType.Cat1:
                        // Pull the Answers out of the new JObject
                        var cat1Answers = (JArray)jsonMessageBody["Answers"];
                        var totals = (JArray)jsonMessageBody["Totals"];
    
                        // Send the answers to be processed
                        await ProcessCat1AnswersAsync(cat1Answers, totals);
                        break;
                }
                Console.WriteLine($"Message {counter} has been processed");
            }
            else
            {
                Console.WriteLine($"Message {counter} was empty, processing next message...");
            }
    
        }
        catch (Exception ex)
        {
            // Error handling
        }
        Console.WriteLine($"There are {totalMessages - counter} messages left to process...");
        counter ++;
    }
    Console.WriteLine("All records have been processed.");
    
    
    Login or Signup to reply.
  2. Refer to the below working code:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    
    public class ReportData
    {
        public int BusinessEntityID { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public double Rate { get; set; }
        public string DueDate { get; set; }
    }
    
    public class Report
    {
        public string Type_Report { get; set; }
        public string Report_Title { get; set; }
        public List<ReportData> Report_Data { get; set; }
    }
    
    public class CompanyInfo
    {
        public string Company { get; set; }
        public string Id { get; set; }
    }
    
    public class RootObject
    {
        public CompanyInfo CompanyInfo { get; set; }
        public List<Report> ReportsToGenerate { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            string json = @"
            [
                {
                    ""CompanyInfo"": {
                        ""Company"": ""AdventureWorks"",
                        ""Id"": ""AW01""
                    },
                    ""ReportsToGenerate"": [
                        {
                            ""Type_Report"": ""Type A Report"",
                            ""Report_Title"": ""Human Resources Report"",
                            ""Report_Data"": [
                                {
                                    ""BusinessEntityID"": 168,
                                    ""FirstName"": ""Garrett"",
                                    ""MiddleName"": ""R"",
                                    ""Rate"": 9.5000
                                },
                                {
                                    ""BusinessEntityID"": 278,
                                    ""FirstName"": ""Garrett"",
                                    ""MiddleName"": ""R"",
                                    ""Rate"": 23.0769
                                }
                            ]
                        },
                        {
                            ""Type_Report"": ""Type B Report"",
                            ""Report_Title"": ""Sales Report"",
                            ""Report_Data"": [
                                {
                                    ""BusinessEntityID"": 282,
                                    ""FirstName"": ""José"",
                                    ""MiddleName"": ""Edvaldo"",
                                    ""DueDate"": ""2011-06-12T00:00:00""
                                },
                                {
                                    ""BusinessEntityID"": 282,
                                    ""FirstName"": ""José"",
                                    ""MiddleName"": ""Edvaldo"",
                                    ""DueDate"": ""2011-06-12T00:00:00""
                                }
                            ]
                        }
                    ]
                }
            ]";
    
            List<RootObject> result = JsonConvert.DeserializeObject<List<RootObject>>(json);
    
            foreach (var rootObject in result)
            {
                Console.WriteLine($"Company:"+rootObject.CompanyInfo.Company, "Id" +rootObject.CompanyInfo.Id);
    
                foreach (var report in rootObject.ReportsToGenerate)
                {
                    Console.WriteLine("Type Report:" +report.Type_Report+"Report Title:"+report.Report_Title);
    
                    foreach (var reportData in report.Report_Data)
                    {
                        Console.WriteLine("BusinessEntityID: "+reportData.BusinessEntityID+ "FirstName:"+reportData.FirstName, "MiddleName:"+reportData.MiddleName +"Rate: " +reportData.Rate+" DueDate: "+reportData.DueDate);
                    }
                }
            }
        }
    }
    

    working code .NETFiddle here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search