Getting JSON values

Discussion in 'Spigot Plugin Development' started by Adam_Playz, Apr 21, 2017.

  1. I want to get a JSON value to Minecraft like something using https://www.mcapi.ca and how would I put into an online JSON file? I am a newbie to JSON so in-depth explanations would be great also please forgive me if I use incorrect terminology.
     
  2. Please use the forums search function, before starting new threads.
     
  3. I personally love GSON its better if you can grasp JSON concepts I also use okhhtp to connect to gson

    Code (Text):
    private static OkHttpClient client = new OkHttpClient();
    public static void main(String[] args){
    for(String str:getUserData("CaptainSparklez")){
    System.out.println(str);
    }
    }
       public static String getJSON(String url) throws IOException {
            Request request = new Request.Builder()
                    .url(url)
                    .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
        }
        public static String[] getUserData(String username){
         String json = null;
            try{
                json = getJSON("https://api.twitch.tv/kraken/users/"+username);
            } catch(IOException e){
                        e.printStackTrace();
            }
            Gson gson = new Gson();
            TwitchTV twitchAPI = gson.fromJson(json, TwitchTV.class);
            return new String[]{
                "Bio: " + twitchAPI.getBio(),
                "Name: " + twitchAPI.getName()

            };
        }

    I just found this scrap code i did last year making a Twitch bot and getting Information about a streamer. I cant find the other classes but check in the Internet they may have Information regarding this
     
  4. I prefer to use the included gson library.

    JsonParser parser = new JsonParser();
    JsonObject o = parser.parse("{\"a\": \"A\"}").getAsJsonObject();
     
    • Like Like x 1
  5. You can do the exact same thing with json-simple :p

    Code (Text):
    JSONObject o = (JSONObject) new JSONParser().parse("{\"a\": \"A\"}");
    System.out.println("a : " + ((String)o.get("a")) + " :)");
    Is not included in the spigot server jar?
     
    • Agree Agree x 1
  6. Pretty sure Json-Simple is not included. Also, JSONObject.toJSONString() is better than casting.
     
  7. It is.
     
  8. Well, that's a surprise.
     
  9. It is
    Depends. If you cast (JSONObject) to the Object JSONObject#get() returns, then you can use that method on it. But that's just more work than directly calling get() and casting it to a String, you'd have to do casting either way as the get method returns Object.