c# foreach json object code example
Example 1: c# json foreach key value
var dict = JObject.Parse(@"{""1"":""Name 1"",""2"":""Name 2""}");
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
foreach(var kv in dict)
{
Console.WriteLine(kv.Key + ":" + kv.Value);
}
Example 2: c# foreach object in array json
public class ChatMessage
{
public string author;
public string content;
public int timestamp;
}
public class ChatResponse
{
public List<ChatMessage> chat;
public bool error;
public string message;
}
ChatResponse response = JsonConvert.DeserializeObject<ChatResponse>(json);
foreach (var message in response.chat)
{
rtbChat.AppendText($"{message.author}: {message.content}\n");
}
Example 3: c# loop through json
public class ChatMessage
{
public string author;
public string content;
public int timestamp;
}
public class ChatResponse
{
public List<ChatMessage> chat;
public bool error;
public string message;
}
var json = @"{"chat":[{"author":"Bob","content":"My name is Bob and I approve this message.","timestamp":1604438166}],"error":false,"message":"Chat fetched."}
";
ChatResponse response = JsonConvert.DeserializeObject<ChatResponse>(json);
foreach (var message in response.chat)
{
rtbChat.AppendText($"{message.author}: {message.content}\n");
}