Home > database >  Retrieve nested data from a json stream using c#
Retrieve nested data from a json stream using c#

Time:01-14

Good Day,

Please note I am not a C# developer, I'm a SQL dba, but I'm currently covering for someone who's left the company, so I need to figure this out. I do understand the basic programming concepts of data types, arrays, loops, conditionals, etc. My issue is with commands and syntax. Everything I have so far, I have through Googling.

I'm successfully calling an api using the below syntax, and receiving the json payload described below.

 var streamTask = client.GetStreamAsync("https://myapi.com");

 var answers = await JsonSerializer.DeserializeAsync<List<Referral>>(await streamTask);

The json returned is

{    
"test": true,
"success": true,
"status": 200,
"message": "Success",
"results": [
    {
        "referral": {
            "id": 1234567890,
            "created_on": "2020-10-19T14:37:34.445Z",
            "accepted_on": "2020-10-19T15:11:58.586Z",
            "reported_pending_on": "2021-10-01T16:45:29.017Z",
            "last_modified_on": "2021-10-01T16:45:29.406Z",
            "status": "Sale Pending"
        },
        "customer": {
            "firstname": "John",
            "lastname": "Smith",
            "email": "[email protected]",
            "phone": "(123) 456-7890"
        },
  {
        "referral": {
            "id": 1234567891,
            "created_on": "2021-07-22T18:36:43.646Z",
            "accepted_on": "2021-07-22T19:08:17.053Z",
            "last_modified_on": "2021-10-01T13:00:22.106Z",
            "status": "Referred",
        },
        "customer": {
            "firstname": "Jane",
            "lastname": "Doe",
            "email": "[email protected]",
            "phone": "(123) 456-7894"
        }
   }
}

I have the following classes

     public class Rootobject
    {
        public bool test { get; set; }
        public bool success { get; set; }
        public int status { get; set; }
        public string message { get; set; }
        public Result[] results { get; set; }
    }

    public class Result
    {
        public Referral referral { get; set; }
        public Customer customer { get; set; }
    }

 public class Referral
    {
        public int id { get; set; }
        public DateTime created_on { get; set; }
        public DateTime accepted_on { get; set; }
        public DateTime reported_pending_on { get; set; }
        public DateTime last_modified_on { get; set; }
        public string status { get; set; }
    }

    public class Customer
    {
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
    }

I'm trying to capture the list of ids under referral.

        foreach (var answer in answers)
            Console.WriteLine(answer.id);

This is as far as I've been able to take it. I've played with this with a simple json string and made it work. But I can't figure out the syntax to drill down to id in the actual json payload. Any help is greatly appreciated.

Thanks, John

CodePudding user response:

I would use Linq and query your deserialized object. Something like this:

using System;
using System.Linq;
using System.Text.Json;
                    
public class Program
{
    public static void Main()
    {
        // i made some changes to json to make valid syntax
        var inData = @"{    
            ""test"": true,
            ""success"": true,
            ""status"": 200,
            ""message"": ""Success"",
            ""results"": [
                {
                    ""referral"": {
                        ""id"": 1234567890,
                        ""created_on"": ""2020-10-19T14:37:34.445Z"",
                        ""accepted_on"": ""2020-10-19T15:11:58.586Z"",
                        ""reported_pending_on"": ""2021-10-01T16:45:29.017Z"",
                        ""last_modified_on"": ""2021-10-01T16:45:29.406Z"",
                        ""status"": ""Sale Pending""
                    },
                    ""customer"": {
                        ""firstname"": ""John"",
                        ""lastname"": ""Smith"",
                        ""email"": ""[email protected]"",
                        ""phone"": ""(123) 456-7890""
                    }
              },
              {
                    ""referral"": {
                        ""id"": 1234567891,
                        ""created_on"": ""2021-07-22T18:36:43.646Z"",
                        ""accepted_on"": ""2021-07-22T19:08:17.053Z"",
                        ""last_modified_on"": ""2021-10-01T13:00:22.106Z"",
                        ""status"": ""Referred""
                    },
                    ""customer"": {
                        ""firstname"": ""Jane"",
                        ""lastname"": ""Doe"",
                        ""email"": ""[email protected]"",
                        ""phone"": ""(123) 456-7894""
                    }
               }
               ]
            }";
        
        var theObject = JsonSerializer.Deserialize<Rootobject>(inData);
        var Ids = theObject.results.Select(i => i.referral.id).ToList();
        
        Console.WriteLine(string.Join(", ",Ids));
        
    }
}
public class Rootobject
    {
        public bool test { get; set; }
        public bool success { get; set; }
        public int status { get; set; }
        public string message { get; set; }
        public Result[] results { get; set; }
    }

    public class Result
    {
        public Referral referral { get; set; }
        public Customer customer { get; set; }
    }

 public class Referral
    {
        public int id { get; set; }
        public DateTime created_on { get; set; }
        public DateTime accepted_on { get; set; }
        public DateTime reported_pending_on { get; set; }
        public DateTime last_modified_on { get; set; }
        public string status { get; set; }
    }

    public class Customer
    {
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
    }

see: https://dotnetfiddle.net/JrcdSX

output:

1234567890, 1234567891

CodePudding user response:

The easiest approaches are:

foreach(var item in results)
{
console.writeline(item[0][0])
}

or:

foreach(var item in results)
{
console.writeline(item["referral"]["id"])
}

CodePudding user response:

Deserialize to your RootObject then access the properties normally, using LINQ to select the relevant data:

var root = await JsonSerializer.DeserializeAsync<RootObject>(await streamTask);

var referralIDs = root.results
    .Select( r => r.referral.id );

foreach( var id in referralIDs )
{
    Console.WriteLine( id );
}

CodePudding user response:

Leave your classes as is, then your receive payload part should look like this:

var streamTask = client.GetStreamAsync("https://myapi.com");
List<Rootobject> rootobject = await JsonSerializer.DeserializeAsync<List<Rootobject>>(await streamTask);

Explaination: you have a class named Rootobject, it contains Result type array named results, that results are containing information about referrals (Referral) & customers (Customer)

And your extraction of id should look like this:

foreach (var item in rootobject[0].results)
{
    Console.WriteLine(item.referral.id);
}

Explaination: You only get one Rootobject, so rootobject[0], it contains results, and each step is new result. An item.referral.id means "For each result get me an id of referral"

And your json should look like this

{
  "test": true,
  "success": true,
  "status": 200,
  "message": "Success",
  "results": [
    {
      "referral": {
        "id": 1234567890,
        "created_on": "2020-10-19T14:37:34.445Z",
        "accepted_on": "2020-10-19T15:11:58.586Z",
        "reported_pending_on": "2021-10-01T16:45:29.017Z",
        "last_modified_on": "2021-10-01T16:45:29.406Z",
        "status": "Sale Pending"
      },
      "customer": {
        "firstname": "John",
        "lastname": "Smith",
        "email": "[email protected]",
        "phone": "(123) 456-7890"
      }
    },
    {
      "referral": {
        "id": 1234567891,
        "created_on": "2021-07-22T18:36:43.646Z",
        "accepted_on": "2021-07-22T19:08:17.053Z",
        "last_modified_on": "2021-10-01T13:00:22.106Z",
        "status": "Referred"
      },
      "customer": {
        "firstname": "Jane",
        "lastname": "Doe",
        "email": "[email protected]",
        "phone": "(123) 456-7894"
      }
    }
  ]
}

Explaination: some braces were missing

  •  Tags:  
  • Related