Java tutorial
// This file is part of the Occyd Android Client // - an Android application for geolocation tagging // Copyright (C) 2008, Andrew Perry (ajperry@pansapiens.com) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package com.pansapiens.occyd; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import android.widget.Toast; public abstract class JSONdecoder { /** * Abstract utility class for parsing JSON objects (as strings) and * returning Java objects. */ public static ArrayList<Post> json2postArray(String json_txt) throws JSONException { /** * Takes an appropriate JSON format string, returned as a response * by the server to a search query, returns an ArrayList * of Post objects. */ ArrayList<Post> post_results = new ArrayList(); if (json_txt != null) { // http://code.google.com/android/reference/org/json/JSONObject.html JSONTokener jsontok = new JSONTokener(json_txt); JSONObject json; String geohash = null; String[] tags = null; // TODO: read these from the JSON too //String key = null; //String user = null; //String desc = null; //URL link = null; // see: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html //Date date = null; // parse "2008-12-31 03:22:23.350798" format date with: // (could have an issue with to many millisecond places SSSSSS .... may need to truncate) // SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // Date date = dateformat.parse(dateString); float lat, lon; json = new JSONObject(jsontok); // catch any error codes in the returned json String result = json.getString("result"); if (!result.equals("done")) { return post_results; } // unpack the json into Post objects, add them to the result list JSONArray posts = json.getJSONArray("posts"); for (int i = 0; i < posts.length(); i++) { JSONObject p = posts.getJSONObject(i); geohash = (String) p.get("geohash"); JSONArray coordinates = p.getJSONArray("coordinates"); lat = (float) coordinates.getDouble(0); lon = (float) coordinates.getDouble(1); JSONArray t = p.getJSONArray("tags"); tags = new String[t.length()]; for (int j = 0; j < t.length(); j++) { tags[j] = t.getString(j); } Post post = new Post(lat, lon, geohash, tags); post_results.add(post); } } return post_results; } }