Adam
Adam

Reputation: 483

Deserialise JSON array object with nested list in C#

I am trying to deserialise the live chat api json response to access the message id and text by filtering using user_type

JSON response

{{
  "events": [
    {
      "type": "agent_details",
      "message_id": 1,
      "timestamp": 1532396384,
      "user_type": "agent",
      "agent": {
        "name": "Adam Harris",
        "job_title": "Support Agent",
        "avatar": "livechat.s3.amazonaws.com/default/avatars/ab5b0666feffd67600206cd519fd77ea.jpg"
      }
    },
    {
      "type": "message",
      "message_id": 3,
      "timestamp": 1532396387,
      "user_type": "visitor",
      "text": "hi"
    }
  ]
}}

JsonOject Class

class JsonLiveChatEvent
    {


        public class Rootobject
        {
            public Event[] events { get; set; }
        }

        public class Event
        {
            public string type { get; set; }
            public int message_id { get; set; }
            public int timestamp { get; set; }
            public string user_type { get; set; }
            public Agent agent { get; set; }
            public string text { get; set; }
        }

        public class Agent
        {
            public string name { get; set; }
            public string job_title { get; set; }
            public string avatar { get; set; }
        }


    }

JsonConverter

string jsonStr= await Api.Chat.GetPendingMessages(visitorID, licenseID, 
var chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);

The chatEvent object will not let me call chatEvent.events.message_id for example. Any help would be greatly appreciated as this is my first time working with json in c#

Upvotes: 1

Views: 941

Answers (3)

er-sho
er-sho

Reputation: 9771

Your json contains more that one curly brackets so you have to first remove those

so your json look like

{
  "events": [
    {
      "type": "agent_details",
      "message_id": 1,
      "timestamp": 1532396384,
      "user_type": "agent",
      "agent": {
        "name": "Adam Harris",
        "job_title": "Support Agent",
        "avatar": "livechat.s3.amazonaws.com/default/avatars/ab5b0666feffd67600206cd519fd77ea.jpg"
      }
    },
    {
      "type": "message",
      "message_id": 3,
      "timestamp": 1532396387,
      "user_type": "visitor",
      "text": "hi"
    }
  ]
}

After that you have to collect message ids depending upon user_type

So then we create enum for that

public enum UserType
        {
            agent, visitor
        }

then we simply check in events that if user type is matches with any of above enum value.

If your json contains multiple events with multiple user types then collect those into List<int>.

If your json contains only single event of each user type then collect them into string variables.

Rootobject chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);

            List<int> agent_message_ids = new List<int>();
            List<int> visitior_message_ids = new List<int>();

            //string agent_message_id = string.Empty;
            //string visitior_message_id = string.Empty;

            foreach (Event e in chatEvent.events)
            {
                if (e.user_type == UserType.agent.ToString())
                {
                    agent_message_ids.Add(e.message_id);
                    //agent_message_id = e.message_id;
                }

                if (e.user_type == UserType.visitor.ToString())
                {
                    visitior_message_ids.Add(e.message_id);
                    //visitior_message_id  = e.message_id;
                }

            }

We simply take a list of integers that store message ids for particular user_type

Try once may it help you

Result:

agent_message_ids:

enter image description here

visitor_message_ids:

enter image description here

Upvotes: 0

Anupam Singh
Anupam Singh

Reputation: 1166

There is nothing to do with JSON, you have parsed the JSON data back to Rootobject. Now you are working with an instance of Rootobject as:

Rootobject chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);
Event event1 = chatEvent.events[0];
Event event2 = chatEvent.events[1];

Also, consider the answer from Mohammad, because above JSON will throw an exception.

Upvotes: 1

Mohammad Karimi
Mohammad Karimi

Reputation: 457

The main problem here is that your json is not valid, there is an extra { in the beginning and an extra } in the end. Then you could deserialize your json with the types you provided

Upvotes: 0

Related Questions