我在Community Shoutbox系统中遇到了麻烦。我有一个API可以将喊叫从数据库中提取出来,但我希望能够将每个单独的喊叫列出到ListBox中。
我的API输出为:
{
"data":[
{
"result":"success",
"username":"Critical Development Owner",
"message":"Test",
"time":"06:16:18 AM"
}
]
}
下面用C#内置的社区Shoutbox系统...
Data data = new Data();
public class Data
{
public List<Shout> Shouts { get; set; }
}
public class Shout
{
public string Username { get; set; }
public string Message { get; set; }
public string Time { get; set; }
}
private void CommunityChat_Load(object sender, EventArgs e)
{
timer.Interval = 10000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
try
{
string shoutsAPI = "API HERE";
var getShout = System.Net.WebRequest.Create(shoutsAPI);
using (WebResponse wrs = getShout.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadLine();
while (!reader.EndOfStream)
{
data = JsonConvert.DeserializeObject<Data>(json);
}
foreach (var shout in data.Shouts)
{
Console.WriteLine($"Username: {shout.Username}");
}
}
}
catch (Exception b)
{
XtraMessageBox.Show("Caught Error:\n" + b, "Error");
}
}
编辑/更新的代码 我一直在向SO以外的人问问题,他们帮助了我实现了这一目标,但是现在我像以前一样感到困惑: 控制台输出:
{
"data":[
{
"result":"success",
"username":"Critical Development Owner",
"message":"Test",
"time":"06:16:18 AM"
}
]
}
Username: Renegade.CommunityChat+Data[]
public class RootObject
{
public Data[] Data { get; set; }
}
public class Data
{
public string Result { get; set; }
public string Username { get; set; }
public string Message { get; set; }
public string Time { get; set; }
}
private void CommunityChat_Load(object sender, EventArgs e)
{
timer.Interval = 10000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
try
{
string shoutsAPI = "API";
var getShout = System.Net.WebRequest.Create(shoutsAPI);
using (WebResponse wrs = getShout.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadLine();
Console.WriteLine(json);
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine($" {obj.Data}");
}
}
catch (Exception b)
{
XtraMessageBox.Show("Caught Error:\n" + b, "Error");
}
}