Skip to content

Instantly share code, notes, and snippets.

@aembleton
Created July 22, 2011 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aembleton/1099083 to your computer and use it in GitHub Desktop.
Save aembleton/1099083 to your computer and use it in GitHub Desktop.
Utility class containing static methods that are useful for reading in and marshalling JSON
package net.blerg.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
/**
* Utility class containing static methods that are useful for reading in and
* marshalling JSON
*
* @author arthur
*
*/
public class JsonUtil {
private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
private static final String UTF8 = "UTF-8";
/**
* Gets the JSON from a given URL with the contents of postData POSTed in
* and marshals it into an object of type T
*
* @param urlString
* The URL to open
* @param classOfT
* Class of the object to marshal the JSON into
* @param postData
* Map of data to POST to the URL
* @return An object of type T if the JSON was successfully retrieved from
* the URL, otherwise null is returned.
*/
public static <T> T getJsonFromUrl(String urlString, Class<T> classOfT, Map<String, String> postData) {
try {
URL url = new URL(urlString);
InputStream inputStream = null;
if (postData != null && postData.size() > 0) {
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(mapToData(postData));
writer.flush();
inputStream = urlConnection.getInputStream();
} else {
inputStream = url.openStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Gson gson = new Gson();
return gson.fromJson(reader, classOfT);
} catch (MalformedURLException e) {
log.error("Could not parse " + urlString + " into a URL object.", e);
} catch (IOException e) {
log.error("Could not open " + urlString, e);
}
return null;
}
/**
* Gets the JSON from a given URL and marshals it into an object of type T
*
* @param urlString
* The URL to open
* @param classOfT
* Class of the object to marshal the JSON into
* @return An object of type T if the JSON was successfully retrieved from
* the URL, otherwise null is returned.
*/
public static <T> T getJsonFromUrl(String urlString, Class<T> classOfT) {
return getJsonFromUrl(urlString, classOfT, null);
}
/**
* URL encodes the keys and values into UTF-8 format and concatenates the
* key=value pairs together with an &. This has been created in order to
* POST data.
*
* @param map
* A map of keys and values to be URL encoded
* @return A string such as key1=foo&key2=bar where key1 and key2 are keys
* in the map and foo and bar are their corresponding values.
*/
private static String mapToData(Map<String, String> map) {
boolean first = true;
String data = "";
for (Entry<String, String> entry : map.entrySet()) {
if (first) {
first = false;
} else {
data += "&";
}
try {
data += URLEncoder.encode(entry.getKey(), UTF8) + "=" + URLEncoder.encode(entry.getValue(), UTF8);
} catch (UnsupportedEncodingException e) {
log.error("URLEncoding failed, with either " + entry.getKey() + " and/or " + entry.getValue(), e);
}
}
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment