2

Im trying to access inner JSON message Array Element as shown below in the sample JSON string.

{"chats":
[
//////////1ST CHAT
{"type":"chat",
"id":"OYTHUUBLB2",
"tickets":[],
"visitor_name":"Shen",
"visitor_id":"value",
"visitor_ip":"val",
"visitor":
             {"id":"",
    "name":"Shen",
    "email":"shen@gmail.com",
    "ip":"val",
    "city":"Brampton",
    "region":"Ontario",
    "country":"Canada",
    "country_code":"CA",
    "timezone":"America/Rainy_River"},
"agents":[
    {"display_name":"Kim",
    "email":"val@email.com",
    "ip":"72."},
    ],
"supervisors":[],
    "rate":"not_rated",
    "duration":213,
    "chat_start_url":"httpsjj",
    "group":[3],
    "started":"Fri 10/27/17 01:12:38 pm",
    "pending":false,
"tags":[],
"timezone":"America/Bogota",
"messages":[
        {
        "author_name":"Kim",
        "text":"Hello Shenelle. How may I help you?",
        "date":"Fri10/27/17 01:12:38 pm",
        "timestamp":1509127958,
        "agent_id":"val",
        "user_type":"agent",
        "type":"message",
        "welcome_message":true,
                     }
        {"author_name":"Shenelle",
        "text":"I would like",
        "date":"Fri 10/27/17 01:12:56 pm",
        "timestamp":1509127976,
        "user_type":"visitor",
        "type":"message"},
                 {
        "author_name":"Shenelle",
        "text":"helooooooooooooooooo",
        "date":"Fri10/27/17 01:15:47 pm",
        "timestamp":1509128147,
        "user_type":"visitor",
        "type":"message"},
                  ]

Here is what i have tried already in C#. I can access the other elements but its just that inner nested JSON message array is my problem. Anyone can help with the code for accessing [text] element? I just want to concat all the iterations on the [text] element on that individual particular ChatIndex. My end result is to concat all [text] element of each of the individual chats.

 //  JObject chatMessage = JObject.Parse(result);
        dynamic chatMessage = JsonConvert.DeserializeObject(result);


     int totalChats = (int)chatMessage["total"];//totalChats gives count of all individual chats

        for(int chatIndex = 0; chatIndex < totalChats; chatIndex++)
        {
            string id = (string)chatMessage["chats"][chatIndex]["id"];
      string city = (string)chatMessage["chats"][chatIndex]["visitor"]["city"];
            string region = (string)chatMessage["chats"][chatIndex]["visitor"]["region"];
            string country = (string)chatMessage["chats"][chatIndex]["visitor"]["country"];
            string visitorName = (string)chatMessage["chats"][chatIndex]["visitor"]["name"];
            string visitorEmail = (string)chatMessage["chats"][chatIndex]["visitor"]["email"];

            Console.WriteLine("ID: "+id+ "\nVisitor Name: " +visitorName+ "\nVisitor Email:"+visitorEmail
               + "\nVisitor City:"+ city + "\nVisitor Region:"+region +"\nCountry of visitor:"+ country);

            //   int messageIndex = chatMessage["chats"][chatIndex]["messages"].length;
            // foreach (var messageIndex in chatMessage.messages)
            //  {
            for (int messageIndex = 0; messageIndex < chatMessage["chats"][chatIndex]["messages"]; messageIndex++) { 

                //   string msg = (string)chatMessage["chats"][chatIndex]["messages"][messageIndex]["author_name"];
           string text = (string)chatMessage["chats"][chatIndex]["messages"][messageIndex]["text"];
               // string.Concat(","+text);
                Console.WriteLine("\n TEXT:"+text);
                            }

            Console.WriteLine(""); //x++;
        }
Aryan Firouzian
  • 1,940
  • 5
  • 27
  • 41
ForzaC
  • 43
  • 8
  • You know that there are some formatting error in json string? some comma(,) are missing – Aryan Firouzian Oct 28 '17 at 23:05
  • @AryanFirouzyan I know, I just copied a snippet from original json string to try and let you guys understand how Messages element was nested. But i can access other elements. its just that inner loop in the code to get all [text] elements and i want to concat them – ForzaC Oct 28 '17 at 23:08
  • Ok, just check second and third items for **messages** value – Aryan Firouzian Oct 28 '17 at 23:10
  • i could access 1st [text] element like this string text = (string)chatMessage["chats"][chatIndex]["messages"][0]["text"]; but that number of inner nest will vary per chat. so i wanted to loop through it to kind of automate the process. – ForzaC Oct 28 '17 at 23:13

2 Answers2

2

Using Newtonsoft.Json and after JsonConvert.DeserializeObject, Here you can go through nested items:

int messageNumber = chatMessage.messages.Count;
for (int i = 0; i < messageNumber; i++)
{
    Console.WriteLine(chatMessage.messages[i].text);
}
Aryan Firouzian
  • 1,940
  • 5
  • 27
  • 41
  • it gives error: microsoft.csharp.runtimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference – ForzaC Oct 28 '17 at 23:40
  • so strange cause when i put this place in place of that inner loop string text = (string)chatMessage["chats"][chatIndex]["messages"][0]["text"]; string text2 = (string)chatMessage["chats"][chatIndex]["messages"][1]["text"]; //Console.WriteLine("\n TEXT:"+ string.Concat("," + text+','+text2)); it prints the first 2 elements concatted as i want it to...but i want it to work in a loop – ForzaC Oct 28 '17 at 23:41
  • So the problem is probably the way how we got the length or count messages. Can you debug to see if you count the number of messages correctly? – Aryan Firouzian Oct 28 '17 at 23:48
  • 1
    It turns out we had to also reference those upper nested elements in the tags. I posted answer just made some changes to your code snippet – ForzaC Oct 28 '17 at 23:56
  • Glad that helped :D – Aryan Firouzian Oct 29 '17 at 00:00
  • ok Thanks bro..working on getting data in Sql server now....Connecting to API's can be fun sometimes i guess – ForzaC Oct 29 '17 at 00:02
2
 int messageNumber = chatMessage["chats"][chatIndex]["messages"].Count;
            for (int i = 0; i < messageNumber; i++)
            {
                string text = (string)chatMessage["chats"][chatIndex]["messages"][i]["text"];
                Console.WriteLine(text);
            }

This solved the problem. Had to get those upper nested elements in place. Turns out all i needed on my original code was to add .Count to chatMessage["chats"][chatIndex]["messages"]

ForzaC
  • 43
  • 8