Solved Get a JSON String of a field

Discussion in 'Spigot Plugin Development' started by Keffisor, Feb 9, 2018.

  1. Hello, I'm trying to get the string "subscriberCount" in the API of YouTube, but my code doesn't work and Idk how I can get it

    Code (Text):
          try
          {
                  String genreJson = IOUtils.toString(new URL("https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + channelId+"&key=AIzaSyAPIvwDhw7wY10PqIbC0GVtEaLJ7MBnKug".replaceAll(" ", "")));
            JSONObject json = (JSONObject)JSONValue.parse(arrayListToString(getContent(genreJson)));
                  JSONArray items = (JSONArray)json.get("items");
          JSONObject j1 = (JSONObject)items.get(0);
          JSONObject jstats = (JSONObject)j1.get("statistics");
            String subs = jstats.get("subscriberCount").toString();
           
     
            if (!subs.equals(p.getUniqueId().toString().replace("-", "")))
            {
              sender.sendMessage("§6asd:§e" + subs);
                }
              }
           
         
          catch (IOException ex)
          {
            ex.printStackTrace();
            sender.sendMessage("§6asd:§e Error");
          }
        }
      }
       
        }
          return true;
          }
    }
     
  2. Here's my method (not the best, but it surely works):
    Code (Java):
    public YTChannelBuilder collectData() {
        YTChannels channels = null;

        InputStream is = null;

        try {
            is = new URL(YouTubeHandler.API_ENDPOINT + "channels?part=snippet,statistics&id=" + id + "&key=" + YouTubeHandler.API_KEY).openStream();

            channels = YouTubeBotPlugin.GSON.fromJson(new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))), YTChannels.class);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignored) {
                }
            }
        }

        if (channels != null) {
            if (channels.getItems().length > 0) {
                PageItem pageItem = channels.getItems()[0];

                this.id = pageItem.getId();
                this.statistics = pageItem.getStatistics();
                this.snippet = pageItem.getSnippet();

                // Lastly, set the username if it haven't already been set
                if (username == null || username.isEmpty()) {
                    this.username = pageItem.getSnippet().getTitle();
                }

                return this;
            }
        }

        this.id = "";
        this.username = "";

        return this;
    }
    PageItem:
    Code (Java):
    /**
     * Project created by ExpDev
     *
     * Could use abstraction, but GSON fucks it up hard, so deal with
     * null values of Snippet, Statistics.
     */

    public class PageItem implements Serializable {

        private transient static final long serialVersionUID = -6169990112332063314L;

        private String kind;
        private String etag;
        private String id;

        private Snippet snippet;
        private Statistics statistics;

        public PageItem(String kind, String etag, String id,
                        Snippet snippet, Statistics statistics) {
            this.kind = kind;
            this.etag = etag;
            this.id = id;

            this.snippet = snippet;
            this.statistics = statistics;
        }

        public String getKind() {
            return kind;
        }

        public String getEtag() {
            return etag;
        }

        public String getId() {
            return id;
        }

        public Snippet getSnippet() {
            return snippet;
        }

        public Statistics getStatistics() {
            return statistics;
        }
    }

    /*
    {
     "kind": "youtube#channelListResponse",
     "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/7k0DWQgAtvXHsl-LDWxHYeWM65Y\"",
     "pageInfo": {
      "totalResults": 1,
      "resultsPerPage": 5
     },
     "items": [
      {
       "kind": "youtube#channel",
       "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/MCoWlFvjCFFg5rqVAWW-H0V6tsg\"",
       "id": "UC_aEa8K-EOJ3D6gOs7HcyNg"
      }
     ]
    }
     */
    Statistics:
    Code (Java):
    /**
     * Project created by ExpDev
     */

    public class Statistics implements Serializable {

        private transient static final long serialVersionUID = -6049901123320963314L;

        private BigInteger viewCount;
        private BigInteger commentCount;
        private BigInteger subscriberCount;
        private BigInteger videoCount;

        private boolean hiddenSubscriberCount;

        public Statistics(BigInteger viewCount, BigInteger commentCount, BigInteger subscriberCount,
                          BigInteger videoCount, boolean hiddenSubscriberCount) {
            this.viewCount = viewCount;
            this.commentCount = commentCount;
            this.subscriberCount = subscriberCount;
            this.videoCount = videoCount;
            this.hiddenSubscriberCount = hiddenSubscriberCount;
        }

        public BigInteger getViewCount() {
            return viewCount;
        }

        public BigInteger getCommentCount() {
            return commentCount;
        }

        public BigInteger getSubscriberCount() {
            return subscriberCount;
        }

        public BigInteger getVideoCount() {
            return videoCount;
        }

        public boolean hasHiddenSubscriberCount() {
            return hiddenSubscriberCount;
        }

        /**
         * Calculates the average views count per video (views / videos)
         *
         * @return Calculated average views count per video
         */

        public BigInteger getAverageViewCount() {
            // Avoiding arithmetic exception with division / by 0
            if (new BigInteger("1").compareTo(viewCount) == 1) {
                return new BigInteger("0");
            }

            return viewCount.divide(videoCount);
        }

    }

    /*
       "statistics": {
        "viewCount": "38350",
        "commentCount": "0",
        "subscriberCount": "153",
        "hiddenSubscriberCount": false,
        "videoCount": "24"
       }
     */
    So basically, just create the objects in java, and use gson for serialization.
     
  3. My code was correct the only problem was that the int of "channelId" was wrong xDD

    Thanks anyways ^^
     

Share This Page