Answers for "java get json from url"

1

java get json from url

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

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

  public static JSONObject readJsonFromUrl(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 = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }
}
Posted by: Guest on July-09-2021
0

java get json from url

//include org.json:json as a dependency
try(BufferedReader br=new BufferedReader(new InputStreamReader(new URL("URL here").openStream()))){
	JSONObject json=new JSONObject(br.lines().collect(Collectors.joining()));
    json.getString("hello");//gets the String of the key named "hello"
    json.getInt("world");//gets the integer value of the key named "world"
    json.getJSONObject("test");//gets the JSONObject value representation of the key "test", you can use the getXXX methods on the returned object
    json.getJSONObject("test").getString("something");
}

/* JSON data:
{
	"hello": "some string",
    "world": 1234,
    "test":{
    	"something": "else"
    }
}
*/
Posted by: Guest on April-09-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language