我試圖訪問內部JSON消息數組元素,如下面示例JSON字符串中所示。在C中訪問消息元素的內部嵌套JSON數組#
{"chats":
[
//////////1ST CHAT
{"type":"chat",
"id":"OYTHUUBLB2",
"tickets":[],
"visitor_name":"Shen",
"visitor_id":"value",
"visitor_ip":"val",
"visitor":
{"id":"",
"name":"Shen",
"email":"[email protected]",
"ip":"val",
"city":"Brampton",
"region":"Ontario",
"country":"Canada",
"country_code":"CA",
"timezone":"America/Rainy_River"},
"agents":[
{"display_name":"Kim",
"email":"[email protected]",
"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]元素的所有迭代。我最終的結果是連接每個單獨聊天的所有[文本]元素。
// 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++;
}
你知道有一些格式錯誤的JSON字符串?一些逗號(,)缺失 –
@AryanFirouzyan我知道,我剛剛從原始json字符串複製了一段代碼,試圖讓你們瞭解Messages元素是如何嵌套的。但我可以訪問其他元素。它只是在代碼中的內部循環來獲取所有[文本]元素,我想連接它們 – ForzaC
好吧,只需檢查**消息的第二和第三項**值 –