我正在尝试访问内部 JSON 消息数组元素,如下面的示例 JSON 字符串所示。
{"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"},
]
这是我已经在 C# 中尝试过的内容。我可以访问其他元素,但它只是内部嵌套的 JSON 消息数组是我的问题。任何人都可以帮助访问 [text] 元素的代码吗?我只想在那个单独的特定 ChatIndex 上连接 [text] 元素上的所有迭代。我的最终结果是连接每个单独聊天的所有 [text] 元素。
// 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++;
}