我目前正在制作Discord机器人。我希望它能够访问具有特定查询的API,然后在聊天中显示响应。为此,我做了这个命令:
commands.CreateCommand("card").Parameter("user", ParameterType.Unparsed).Do(async (e) =>
{
string message = e.Args[0];
await e.Channel.SendMessage("https://omgvamp-hearthstone-v1.p.mashape.com/cards/" + message + "?collectible=1");
var r = await Get<RootObject>("https://omgvamp-hearthstone-v1.p.mashape.com/cards/" + message + "?collectible=1");
Console.Write("Hold it!\n");
await e.Channel.SendMessage(r.img);
});
它引用的功能:
public async Task<RootObject> Get<RootObject>(string url)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation("X-Mashape-Key", "xxxxx");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
Console.Write("Hang on!\n");
var json = await client.GetStringAsync(url);
Console.Write("Not so fast!\n");
return JsonConvert.DeserializeObject<RootObject>(json);
}
}
但是当我发送命令时,它只发回第一个链接以及挂起和不那么快的消息。我想要的消息,r.img,只是没有发送。如何更改代码以便它以我想要的信息响应?
顺便提一下:
[
{
"cardId":"EX1_572",
"dbfId":"1186",
"name":"Ysera",
"cardSet":"Classic",
"type":"Minion",
"faction":"Neutral",
"rarity":"Legendary",
"cost":9,
"attack":4,
"health":12,
"text":"At the end of your turn, add_a Dream Card to_your hand.",
"flavor":"Ysera rules the Emerald Dream. Which is some kind of green-mirror-version of the real world, or something?",
"artist":"Gabor Szikszai",
"collectible":true,
"elite":true,
"race":"Dragon",
"playerClass":"Neutral",
"img":"http://media.services.zam.com/v1/media/byName/hs/cards/enus/EX1_572.png",
"imgGold":"http://media.services.zam.com/v1/media/byName/hs/cards/enus/animated/EX1_572_premium.gif",
"locale":"enUS"
}
]
和RootObject.cs:
namespace DiscordBot
{
public class RootObject
{
public string cardId { get; set; }
public string dbfId { get; set; }
public string name { get; set; }
public string cardSet { get; set; }
public string type { get; set; }
public string faction { get; set; }
public string rarity { get; set; }
public int cost { get; set; }
public int attack { get; set; }
public int health { get; set; }
public string text { get; set; }
public string flavor { get; set; }
public string artist { get; set; }
public bool collectible { get; set; }
public bool elite { get; set; }
public string race { get; set; }
public string playerClass { get; set; }
public string img { get; set; }
public string imgGold { get; set; }
public string locale { get; set; }
}
}
答案 0 :(得分:0)
你提供的Json以 [开头,表示它是一个数组,而不是以 {开头,表示一个对象。
所以而不是
JsonConvert.DeserializeObject<RootObject>(json);
你应该使用
JsonConvert.DeserializeObject<RootObject[]>(json);