【问题标题】:Json to .net translation [closed]Json 到 .net 的翻译 [关闭]
【发布时间】:2017-03-09 09:47:02
【问题描述】:

我目前正在开发一个不和谐的机器人,我想“翻译”这个:

[
   {
      "command" : "ping",
      "response" : "pong"
   },
   {
      "command" : "hi",
      "response" : "hello"
   }
]

到看起来像这样的 .net 代码

    private void RegisterPingCommand()
    {
        commands.CreateCommand("ping")
            .Do(async (e) =>
            {
                await e.Channel.SendMessage("pong");
            });
    } }
    private void RegisterHiCommand()
    {
        commands.CreateCommand("Hi")
            .Do(async (e) =>
            {
                await e.Channel.SendMessage("Hello");
            });
    } }

【问题讨论】:

  • 听起来不错。到目前为止,您尝试了什么,哪些没有按预期工作?
  • 问题是,我什么都没试过,因为我对这一切都很陌生,不知道该怎么做。
  • 可以理解,但 Stack Overflow 不是教学服务。但是,如果您能够提出具体问题,我们可以做的是在遇到困难时为您提供帮助。请查看如何提供minimal reproducible example
  • JSON 通常用于序列化/反序列化对象,不做 RPC
  • @EJoshuaS 我不同意。它只是一种内容格式。它不需要 REST。

标签: c# discord


【解决方案1】:

您可以使用 Json.Net 反序列化您的 json。然后循环你的结果。

var actions = JsonConvert.DeserializeObject<List<MyAction>>(json);
foreach(var x in actions)
{
    commands.CreateCommand(x.command)
    .Do(async (e) =>
    {
        await e.Channel.SendMessage(x.response);
    });
}

public class MyAction
{
    public string command { get; set; }
    public string response { get; set; }
}

【讨论】:

    猜你喜欢
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2023-03-04
    • 1970-01-01
    • 2014-01-15
    • 2011-12-23
    相关资源
    最近更新 更多