JSON code examples?

Put your problem here if it does not fit any of the other categories.

JSON code examples?

Postby Mike.Adams » Mon Mar 07, 2011 9:23 pm

I found this on good, but is there a better way to do this?

Code: Select all
String result = queryRESTurl("http://location/of/wellformed/json.json");

        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", "There was an error parsing the JSON", e);
        }



public String queryRESTurl(String url) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response;
       
        try {
                response = httpclient.execute(httpget);
                Log.i(TAG, "Status:[" + response.getStatusLine().toString() + "]");
                HttpEntity entity = response.getEntity();
               
                if (entity != null) {
                       
                        InputStream instream = entity.getContent();
                        String result = RestClient.convertStreamToString(instream);
                        Log.i(TAG, "Result of converstion: [" + result + "]");
                       
                        instream.close();
                        return result;
                }
        } catch (ClientProtocolException e) {
                Log.e("REST", "There was a protocol based error", e);
        } catch (IOException e) {
                Log.e("REST", "There was an IO Stream related error", e);
        }
       
        return null;
}

http://androiddevcentral.com/source-cod ... eb-service
Hi I'm Mike. Checkout my source code, projects and work here and let me know what you think.

Feel free to also upload and submit your code/projects there for all to see and find!
Mike.Adams
Developer
Developer
 
Posts: 26
Joined: Mon Mar 07, 2011 9:19 pm
Location: New York

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: Yahoo [Bot] and 20 guests