JSON数组如何读取第一个元素?

12

我有一个用于检查Twitch关注用户的JSON数组。我想仅获取第一个日期(因为那是最新的日期), 但每次执行我的代码时,它都只会切换到下一个“日期”。

我该如何更改这个问题?

代码;

import org.jibble.pircbot.*;
import org.json.JSONException;
import org.json.simple.*;
import org.json.simple.parser.*;
import org.w3c.dom.ranges.RangeException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.*;



////////////////////////////////////////////////////////////////////////////////////
                // Twitch Follower Ticker
                ////////////////////////////////////////////////////////////////////////////////////

                private String readAll4(Reader rd) throws IOException {
                    StringBuilder sb = new StringBuilder();
                    int cp;
                    while ((cp = rd.read()) != -1) {
                      sb.append((char) cp);
                    }
                    return sb.toString();
                  }

                  public JSONObject readJsonFromUrl4(String url) throws IOException, JSONException {
                    InputStream is = new URL(url).openStream();
                    try {
                      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                      String jsonText = readAll4(rd);
                      JSONObject json = new JSONObject(jsonText);
                      return json;
                    } finally {
                      is.close();
                    }
                  }

                  public void FollowerTicker() throws IOException, JSONException {
                    json = readJsonFromUrl2("https://api.twitch.tv/kraken/channels/"+ownerchannel+"/follows");

                    JSONArray followerarray = json.getJSONArray("follows");

                    for(int n = 0; n < followerarray.length(); n++)
                    {
                        JSONObject followertime = followerarray.getJSONObject(n);
                        String ftime = followertime.getString("created_at");


                        int maxfollows = json.getInt("_total");


                    System.out.println("Total Follows : "+maxfollows);
                    System.out.println("Loop Follow Date: "+ftime);

                    }
              }

编辑后的代码;

                private String readAll4(Reader rd) throws IOException {
                    StringBuilder sb = new StringBuilder();
                    int cp;
                    while ((cp = rd.read()) != -1) {
                      sb.append((char) cp);
                    }
                    return sb.toString();
                  }

                  public JSONObject readJsonFromUrl4(String url) throws IOException, JSONException {
                    InputStream is = new URL(url).openStream();
                    try {
                      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                      String jsonText = readAll4(rd);
                      JSONObject json = new JSONObject(jsonText);
                      return json;
                    } finally {
                      is.close();
                    }
                  }

                  public void FollowerTicker() throws IOException, JSONException {
                    json = readJsonFromUrl2("https://api.twitch.tv/kraken/channels/"+ownerchannel+"/follows");

                    JSONArray followerarray = json.getJSONArray("follows");

//                  for(int n = 0; n < followerarray.length(); n++)
                    {
                        JSONObject followertime = followerarray.getJSONObject(0);
                        String ftime = followertime.getString("created_at");
                        String fname = followertime.getJSONObject("user").getString("display_name");  
                        int maxfollows = json.getInt("_total");


                    System.out.println("Total Follows zurzeit: "+maxfollows);
                    System.out.println("Neustes Follower - Datum: "+ftime);
                    System.out.println("Neuster Follower Name: "+fname);

                    }
              }

如果你只想获取第一个日期,只需使用 followerarray.getJSONObject(0); 获取JSONArray中的第一个元素,而不需要进行循环。我不知道这是否符合你的要求。 - tonga
哇,这正是我正在寻找的!谢谢你!=) - user3220962
2个回答

16

只需避免循环做一些像这样的事情:

private static int FIRST_ELEMENT = 0;

public static void main(String[] args) {
    JSONArray json = new JSONArray("[{\"Hello1\":\"1\"},{\"Hello2\":\"2\"}]");

    if (json.length() > 0) {
        System.out.println("First: " + json.getJSONObject(FIRST_ELEMENT).toString());// parse the date instead of toString()
    }
}

我不确定这是否完全符合您的要求 ;)


我使用了Tonga告诉我的方法,现在它按照我想要的方式工作了。无论如何还是谢谢!=) - user3220962
事实上,这个方法完全相同,只是我的答案太晚了 ;) - Yser
哦,好吧,我现在发现一个错误。 一旦我的代码被使用,它会打印日期+名称,像30倍一样。 它每次都是第一个:o有什么帮助可以修复它吗? - user3220962
哦,是我的错:D 但还有一件事我不明白;一旦它发布日期+名称,它也会发布整个JSON :/ 我已经更新了上面的整个代码。 - user3220962
我不熟悉API,也不了解你的所有代码,但一般来说,这应该是工作流程(不是最佳解决方案):1. 在定义的时间间隔内轮询最新消息(如果时间间隔很短,您可能不会错过任何消息,但我猜API提供者不再喜欢您)2. 检查的最新消息是否比的“最新”消息更新(您必须保存每次轮询的消息并比较日期)3. 如果消息更新,则发送IRC消息,否则不执行任何操作。 - Yser
显示剩余3条评论

4
免费获取更简短的答案!
JSONObject first = new JSONArray(
    "[{\"Key1\":\"Value1\"}]").
  getJSONObject(0);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接