【问题标题】:Parsing Json Arrays from an API for an IRC Bot and Creating an initial message从 IRC Bot 的 API 解析 Json 数组并创建初始消息
【发布时间】:2017-11-19 21:55:07
【问题描述】:

第一个问题:

我正在使用实现 OpenWeatherMap API 的 Pircbot 在 Java 中创建一个 IRC 机器人,但我无法显示机器人在连接到频道后立即发送的初始消息。我希望此消息显示有关如何使用 API 的说明。我尝试在构造函数中执行此操作,但这不起作用,因为您需要onMessage method 中看到的通道字符串。我搜索了Pircbot website 中的方法,但找不到此方法。

第二个问题:

我在实现 OpenWeatherMap 的 API 的某个部分时遇到问题。对于"weather",它使用 JsonArray,我不完全确定如何解析它。因为它是一个 API 而不是文件,所以我在网上找到的解决方案一直不起作用,因为它们在我尝试使用 JsonParser 时使用了 JsonReader。这是我试图解析这个数组的代码。我正在尝试从“天气”JsonArray 访问“主”键。

static String parseJsonWeatherMain(String json)
{
    JsonElement jelement = new JsonParser().parse(json);

    JsonObject MasterWeatherObject = jelement.getAsJsonObject();

    JsonArray weatherArray = MasterWeatherObject.getAsJsonArray("weather");
    String main = weatherArray.get(1).getAsString();

    return main;
}

作为参考,这是我解析来自 JsonObjects 的其他键的方式:

static double parseJsonWindGust(String json)
{
    JsonElement jelement = new JsonParser().parse(json);
    JsonObject  MasterWeatherObject = jelement.getAsJsonObject();

    JsonObject windObject = MasterWeatherObject.getAsJsonObject("wind");
    double gust = windObject.get("gust").getAsDouble();

    return gust;
}

所以关于如何解析这个 JsonArray 有什么想法吗?我希望“主要”和“描述”键是准确的。

【问题讨论】:

    标签: java json irc openweathermap


    【解决方案1】:

    嗯.. 我不是真正的 Java 开发人员,但我会试一试。

    问题 1: bot 加入频道时发布消息

    这听起来像是经典的onJoin 事件。

    来自 PircBot 文档

    protected void onJoin(String channel,
                          String sender,
                          String login,
                          String hostname)
    

    每当有人(可能是我们)加入频道时,都会调用此方法 我们正在进行中。

    该方法在 PircBot 中的实现 抽象类不执行任何操作,并且可以根据需要被覆盖。

    参数:

    频道 - 某人加入的频道。
    sender - 加入频道的用户的昵称。
    login - 加入频道的用户的登录名。
    主机名 - 加入频道的用户的主机名。

    问题2:从JArray中的JObject中提取main属性。

    你已经接近解决方案了,你只是忘记了一个非常基本的东西。

    weather 是一个对象数组,因此您应该期望weatherArray.get(1) 将返回一个对象,然后您应该应用.get("main") 来提取名为“main”的json 对象属性,只有你可以申请.getAsString(),因为它是一个普通的字符串。

    代码(未经测试,但思路可以理解)

    JsonArray weatherArray = MasterWeatherObject.getAsJsonArray("weather");
    for (int i = 0; i < weatherArray.size(); i++) {
        String main = weatherArray.get("main").getAsString();
        System.out.println(main);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-02
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 2014-01-12
      • 2011-05-12
      • 2016-02-20
      相关资源
      最近更新 更多