Java JSON 数组读取第一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21970492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:45:08  来源:igfitidea点击:

JSON array Read first element?

javaarraysjson

提问by user3220962

I got an JSON Array for my Twitch Following user checker. I would like to get only the first date (cause thats the newest one) out of the array but everytime my code gets executed it just swap to the next "date" then.

我的 Twitch Follow 用户检查器得到了一个 JSON 数组。我只想从数组中获取第一个日期(因为那是最新的一个),但是每次我的代码被执行时,它只是交换到下一个“日期”。

How can i change this?

我怎样才能改变这个?

Code;

代码;

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);

                    }
              }

edited Code;

编辑代码;

                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);

                    }
              }

采纳答案by Yser

Just dont loop and do something like that:

只是不要循环并执行类似的操作:

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()
    }
}

iam not sure if this is exactly what you want ;)

我不确定这是否正是您想要的;)

回答by Zon

Get shorter answer for free!

免费获得更短的答案!

JSONObject first =
  new JSONArray(
    "[{\"Key1\":\"Value1\"}]").
  getJSONObject(0);