A useful little snippet for getting a JSONObject from a REST web service.

The function

The function itself is quite simple. It take the response from the REST url and if a response is found, it converts it into a string and returns it.

public String queryREST( String resturl ) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet( resturl );
    HttpResponse response;

    try {
        response = httpclient.execute( httpget );
        Log.i( TAG, "Status Line: " + response.getStatusLine().toString() );
        HttpEntity entity = response.getEntity();

        if ( entity != null ) {
            InputStream instream = entity.getContent();
            String result = RestClient.convertStreamToString( instream );
            Log.i( TAG, "Result: " + result );

            instream.close();
            return result;
        }
    } catch ( ClientProtocolException e ) {
        Log.e( "REST", "Protocol  error encountered", e );

    } catch ( IOException e ) {
        Log.e( "REST", "IO error encountered", e );
    }

    return null;
}

Example

Start by getting the results of the REST request:

String result = queryREST("http://example.com/rest.url");

Then, convert the result into a JSONObject and iterate the values to turn them into a JSON string. As an example here I've output the JSON format to the log.

try {
    JSONObject json = new JSONObject( result );
    JSONArray nameArray = json.names();
    JSONArray valArray = json.toJSONArray( nameArray );
    for ( int i = 0; i < valArray.length(); i++ ) {
        Log.i( TAG, "<jsonname" + i + ">\\n" + nameArray.getString(i) + "\\n</jsonname" + i + ">\\n" + "<jsonvalue" + i + ">\\n" + valArray.getString(i) + "\\n</jsonvalue"    + i + ">");
    }
}
catch ( JSONException e ) {
    Log.e("JSON", "Error parsing JSON", e);
}