c# - C#。我将如何获取随机 ID,然后获取 largeImgURL
问题描述
我已经尝试了很多事情,但我的大脑现在无法正常工作,我不知道该怎么办了。我已经搜索了互联网,但我没有找到任何可以帮助我的东西。
如果您想要 JSON API 链接,我正在尝试使用 Hits.ID 获取随机搜索结果并从 Hit 获取大图像 URL,以便您可以更好地了解我正在尝试做什么。
搜索命令
[Command("search")]
public async Task Search(CommandContext ctx, string args)
{
WebClient n = new WebClient();
var json = n.DownloadString("https://pixabay.com/api/?key=###################&q=" + args + "&image_type=photo&pretty=true");
var root = JsonConvert.DeserializeObject<Root>(json);
var builder = new DiscordEmbedBuilder
{
Color = DiscordColor.Rose,
Description = "Search Result",
};
foreach (Hit hit in root.hits)
{
builder.WithImageUrl(hit.largeImageURL);
}
await ctx.RespondAsync(embed: builder.Build());
}
获取设置
public class Hit
{
public string largeImageURL { get; set; }
public int webformatHeight { get; set; }
public int webformatWidth { get; set; }
public int likes { get; set; }
public int imageWidth { get; set; }
public int id { get; set; }
public int user_id { get; set; }
public int views { get; set; }
public int comments { get; set; }
public string pageURL { get; set; }
public int imageHeight { get; set; }
public string webformatURL { get; set; }
public string type { get; set; }
public int previewHeight { get; set; }
public string tags { get; set; }
public int downloads { get; set; }
public string user { get; set; }
public int favorites { get; set; }
public int imageSize { get; set; }
public int previewWidth { get; set; }
public string userImageURL { get; set; }
public string previewURL { get; set; }
}
public class Root
{
public int totalHits { get; set; }
public List<Hit> hits { get; set; }
public int total { get; set; }
}
解决方案
要从命中列表中获得随机命中,您可以使用 Linq 来获得这样的结果。
Hit randomHit = root.hits.ElementAt(new Random().Next(x.Count));
var randomUrl = randomHit.largeImageURL;
ElementAt
为您提供特定索引处的元素。使用 0 和该列表中的总命中数之间的随机数,您可以获得随机命中。一旦你有了它,你就可以得到那个对象的 userImageUrl。
推荐阅读
- node.js - Meteor Docker Node.js 版本不匹配
- android - 在java类中获取活动结果
- javascript - 组合 Javascript 对象
- vue.js - 从第三方 API 设置 cookie
- shippo - 如果 transaction.carrier_account 和 transaction.shipment.carrier_account 冲突,Shippo 交易 API 中的预期行为是什么?
- reactjs - 如何在蚂蚁设计中链接两个表格的分页?
- apache-kafka - 单个消费者可以从 kafka 主题的多个分区中读取吗?
- mysql - 模式匹配可以在 MySQL 中用于连续行吗?
- soap - 按行设置inventorySubsidiary和inventoryLocation
- pandas - model.fit validation_set ValueError:DataFrame 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()