Greybeard
Greybeard

Reputation: 67

Deserialize Json Object with C#

I am working with the Telnyx api. One of the api responses returns data that looks like this:

    {
  "data": {
    "event_type": "fax.received",
    "id": "e15c28d4-147e-420b-a638-2a2647315577",
    "occurred_at": "2021-11-19T16:37:02.863682Z",
    "payload": {
      "call_duration_secs": 35,
      "connection_id": "1771912871052051547",
      "direction": "inbound",
      "fax_id": "2a168c93-3db5-424b-a408-b70a3da625bc",
      "from": "+12399999999",
      "media_url": "https://s3.amazonaws.com/faxes-prod/999",
      "page_count": 1,
      "partial_content": false,
      "status": "received",
      "to": "+12399999999",
      "user_id": "dc6e79fa-fe3b-462b-b3a7-5fb7b3111b8a"
    },
    "record_type": "event"
  },
  "meta": {
    "attempt": 1,
    "delivered_to": "https://webhook.site/27ef892c-c371-4976-ae22-22deea57080e"
  }
}

I have read articles on deserializing json to a class object, but I am confused with how to deserialize the payload object within the data. Any help would be appreciated.

Upvotes: 2

Views: 2367

Answers (1)

Leandro Bardelli
Leandro Bardelli

Reputation: 11578

Import Newtonsoft.Json from Nuget

Use this:

 Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(Your_Response_From_API); 

Create the following classes:

        public class Payload
        {
            public int call_duration_secs { get; set; }
            public string connection_id { get; set; }
            public string direction { get; set; }
            public string fax_id { get; set; }
            public string from { get; set; }
            public string media_url { get; set; }
            public int page_count { get; set; }
            public bool partial_content { get; set; }
            public string status { get; set; }
            public string to { get; set; }
            public string user_id { get; set; }
        }
    
        public class Data
        {
            public string event_type { get; set; }
            public string id { get; set; }
            public DateTime occurred_at { get; set; }
            public Payload payload { get; set; }
            public string record_type { get; set; }
        }
    
        public class Meta
        {
            public int attempt { get; set; }
            public string delivered_to { get; set; }
        }
    
        public class Root
        {
            public Data data { get; set; }
            public Meta meta { get; set; }
        }

You can of course, rename your "Root" class

Upvotes: 3

Related Questions