Created
October 27, 2017 04:18
-
-
Save bapspatil/58084e03512368302eb22ddd26b4b132 to your computer and use it in GitHub Desktop.
Load Json from local file and URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
** Created by bapspatil | |
*/ | |
// Load JSON from URL | |
public static String loadJsonFromUrl(URL url) throws IOException { | |
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); | |
try { | |
InputStream in = urlConnection.getInputStream(); | |
Scanner scanner = new Scanner(in); | |
scanner.useDelimiter("\\A"); | |
boolean hasInput = scanner.hasNext(); | |
String response = null; | |
if (hasInput) { | |
response = scanner.next(); | |
} | |
scanner.close(); | |
return response; | |
} finally { | |
urlConnection.disconnect(); | |
} | |
} | |
// Load JSON from local file | |
public String loadJSONFromAsset() { | |
String json = null; | |
try { | |
// Replace getAssets() with getResources if you're storing your JSON file in the res directory | |
InputStream is = getActivity().getAssets().open("yourfile.json"); | |
int size = is.available(); | |
byte[] buffer = new byte[size]; | |
is.read(buffer); | |
is.close(); | |
json = new String(buffer, "UTF-8"); | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
return null; | |
} | |
return json; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment