Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject getJSONArray.

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:com.pansapiens.occyd.JSONdecoder.java

/**
* Abstract utility class for parsing JSON objects (as strings) and
* returning Java objects.// w  w  w  .ja  va 2  s .c  o m
*/
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;
}

From source file:net.jmhertlein.mcanalytics.console.gui.LoginPane.java

private void loadHostPanes(JSONObject config) {

    if (config.has("hosts")) {
        JSONArray hosts = config.getJSONArray("hosts");
        for (int i = 0; i < hosts.length(); i++) {
            JSONObject host = hosts.getJSONObject(i);
            HostEntry entry = HostEntry.fromJSON(host);
            try {
                entry.setHasCert(trust.containsAlias(entry.getUrl() + "-private"));
            } catch (KeyStoreException ex) {
                Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            }//  w  w  w . j av  a  2s  . com
            hostList.getItems().add(entry);
        }
    }

    if (!hostList.getItems().isEmpty())
        hostList.getSelectionModel().select(0);
}

From source file:com.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java

/**
 * Gets table headers from the JSON server response.
 * //from w ww .ja v a  2s .co  m
 * @param responseJSON
 *            the JSON response
 * @return the headers
 */
private String[] getTableHeaders(JSONObject responseJSON) {
    String[] cols = null;
    try {
        JSONArray colsArray = responseJSON.getJSONArray("cols");
        cols = new String[colsArray.length()];
        JSONObject fieldObj;
        for (int i = 0; i < colsArray.length(); i++) {
            fieldObj = (JSONObject) colsArray.get(i);
            cols[i] = fieldObj.optString("name");
        }
    } catch (JSONException e) {
        workspace.showErrorMessage(i18n.getString("jsonUtil.columnNameError"));
    }
    return cols;
}

From source file:com.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java

/**
 * Gets the table body in the JSON server response and calls
 * {@link #convertArray(int, int, JSONArray)}.
 * /*from   www .  j  a v a 2 s .c  o  m*/
 * @param responseJSON
 *            the JSON response
 * @return the body content
 */
private String[][] getTableBody(JSONObject responseJSON, int columns) {
    try {
        JSONArray dataArray = responseJSON.getJSONArray("data");
        if (dataArray != null) {
            int rows = dataArray.length();
            if (rows > 0) {
                return convertArray(rows, columns, dataArray);
            }
        }
    } catch (JSONException e) {
        workspace.showErrorMessage(i18n.getString("jsonUtil.dataError") + "\n" + e.toString());
    } catch (ArrayStoreException e) {
        workspace.showErrorMessage(e.toString());
    }
    return null;
}

From source file:fr.pasteque.client.sync.SendProcess.java

private boolean parseCustomer(JSONObject resp) {
    try {//from  w ww  . j  a  v  a 2s . c om
        // Were customers properly send ?
        JSONObject o = resp.getJSONObject("content");
        JSONArray ids = o.getJSONArray("saved");
        int createdCustomerSize = Data.Customer.createdCustomers.size();
        for (int i = 0; i < createdCustomerSize; i++) {
            String tmpId = Data.Customer.createdCustomers.get(i).getId();
            String serverId = ids.getString(i);
            if (tmpId == null)
                continue; // Should never happen.
            // Updating local info
            for (Customer c : Data.Customer.customers) {
                if (c.getId().equals(tmpId)) {
                    c.setId(serverId);
                    break;
                }
            }
            for (Ticket t : Data.Session.currentSession(this.ctx).getTickets()) {
                Customer c = t.getCustomer();
                if (c != null && c.getId().equals(tmpId)) {
                    c.setId(serverId);
                }
            }
            for (Receipt r : Data.Receipt.getReceipts(this.ctx)) {
                Customer c = r.getTicket().getCustomer();
                if (c != null && c.getId().equals(tmpId)) {
                    c.setId(serverId);
                }
            }
            Data.Customer.resolvedIds.put(tmpId, serverId);
        }
        // Sending Customer completed
        Data.Customer.createdCustomers.clear();
        Data.Customer.save(this.ctx);
        Data.Session.save(this.ctx);
        Data.Receipt.save(this.ctx);
        Log.i(LOG_TAG, "Customer Sync: Saved new local customer ids");
        this.sendCustomer = false;
        this.subprogress = 0;
        SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_DONE);
        instance.nextArchive();
        return true;
    } catch (JSONException e) {
        // Customer not send properly.
        Log.i(LOG_TAG, "Error while parsing customer result", e);
        SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED);
    } catch (IOError e) {
        Log.i(LOG_TAG, "Could not save customer data in parse customer", e);
        SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED);
    }
    return false;
}

From source file:conroller.CommentController.java

public static ArrayList<CommentModel> viewComment() throws IOException, JSONException {
    phpConnection.setConnection(//from   ww w .j av a  2 s  . c o  m
            "http://itmahaweliauthority.net23.net/MahaweliAuthority/CommentPHPfiles/CommentGetView.php");
    String feedbackId, userName, typeOfUser, tankName, massage;
    ArrayList<CommentModel> arrayList = new ArrayList<>();
    JSONObject jSONObject = new JSONObject(phpConnection.readData());
    JSONArray array = jSONObject.getJSONArray("server_response");
    for (int i = 0; i < array.length(); i++) {
        JSONObject details = array.getJSONObject(i);
        try {
            feedbackId = String.valueOf(details.getString("feedbackId"));
        } catch (Exception ex) {
            feedbackId = null;
        }
        try {
            userName = String.valueOf(details.getString("userName"));
        } catch (Exception ex) {
            userName = null;
        }
        try {
            typeOfUser = String.valueOf(details.getString("typeOfUser"));
        } catch (Exception ex) {
            typeOfUser = null;
        }
        try {
            tankName = String.valueOf(details.getString("tankName"));
        } catch (Exception ex) {
            tankName = null;
        }
        try {
            massage = String.valueOf(details.getString("massage"));
        } catch (Exception ex) {
            massage = null;
        }
        CommentModel model = new CommentModel(feedbackId, userName, typeOfUser, tankName, massage);
        arrayList.add(model);
    }
    return arrayList;
}

From source file:com.swisscom.android.sunshine.data.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.// w w w . ja  v  a  2s .c  o  m
 */
private Void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";
    final String OWM_COORD_LAT = "lat";
    final String OWM_COORD_LONG = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_DATETIME = "dt";
    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
    String cityName = cityJson.getString(OWM_CITY_NAME);
    JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD);
    double cityLatitude = coordJSON.getLong(OWM_COORD_LAT);
    double cityLongitude = coordJSON.getLong(OWM_COORD_LONG);

    Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

    // Insert the location into the database.
    long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    // Get and insert the new weather information into the database
    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

    for (int i = 0; i < weatherArray.length(); i++) {
        // These are the values that will be collected.

        long dateTime;
        double pressure;
        int humidity;
        double windSpeed;
        double windDirection;

        double high;
        double low;

        String description;
        int weatherId;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        dateTime = dayForecast.getLong(OWM_DATETIME);

        pressure = dayForecast.getDouble(OWM_PRESSURE);
        humidity = dayForecast.getInt(OWM_HUMIDITY);
        windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
        windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

        // Description is in a child array called "weather", which is 1 element long.
        // That element also contains a weather code.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);
        weatherId = weatherObject.getInt(OWM_WEATHER_ID);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);

        ContentValues weatherValues = new ContentValues();

        weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID);
        weatherValues.put(WeatherEntry.COLUMN_DATETEXT,
                WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
        weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
        weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
        weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
        weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
        weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
        weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
        weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
        weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

        cVVector.add(weatherValues);
    }
    if (cVVector.size() > 0) {
        ContentValues[] cvArray = new ContentValues[cVVector.size()];
        cVVector.toArray(cvArray);
        int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data");
    }
    return null;
}

From source file:cn.code.notes.gtask.remote.GTaskManager.java

private void addLocalNode(Node node) throws NetworkFailureException {
    if (mCancelled) {
        return;//from w w w.j  a v  a 2 s.c o m
    }

    SqlNote sqlNote;
    if (node instanceof TaskList) {
        if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
            sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
        } else if (node.getName()
                .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
            sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
        } else {
            sqlNote = new SqlNote(mContext);
            sqlNote.setContent(node.getLocalJSONFromContent());
            sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
        }
    } else {
        sqlNote = new SqlNote(mContext);
        JSONObject js = node.getLocalJSONFromContent();
        try {
            if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
                JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
                if (note.has(NoteColumns.ID)) {
                    long id = note.getLong(NoteColumns.ID);
                    if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
                        // the id is not available, have to create a new one
                        note.remove(NoteColumns.ID);
                    }
                }
            }

            if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
                JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    if (data.has(DataColumns.ID)) {
                        long dataId = data.getLong(DataColumns.ID);
                        if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
                            // the data id is not available, have to create
                            // a new one
                            data.remove(DataColumns.ID);
                        }
                    }
                }

            }
        } catch (JSONException e) {
            Log.w(TAG, e.toString());
            e.printStackTrace();
        }
        sqlNote.setContent(js);

        Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
        if (parentId == null) {
            Log.e(TAG, "cannot find task's parent id locally");
            throw new ActionFailureException("cannot add local node");
        }
        sqlNote.setParentId(parentId.longValue());
    }

    // create the local node
    sqlNote.setGtaskId(node.getGid());
    sqlNote.commit(false);

    // update gid-nid mapping
    mGidToNid.put(node.getGid(), sqlNote.getId());
    mNidToGid.put(sqlNote.getId(), node.getGid());

    // update meta
    updateRemoteMeta(node.getGid(), sqlNote);
}

From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java

private FeatureCollection decodeFeatureCollection(JSONObject object) throws JSONException {

    FeatureCollection fCollection = null;

    JSONArray array = object.getJSONArray("features");
    if (array != null) {
        fCollection = new FeatureCollection();
        for (int i = 0; i < array.length(); i++) {
            JSONObject o = array.getJSONObject(i);
            if (o.get("type").equals("Feature")) {
                Feature f = this.decodeFeature(o);
                fCollection.addFeature(f);
            }//from   w ww  .j  a  va  2 s. com
        }
    }

    return fCollection;
}

From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java

private IGeometry decodeGeometry(JSONObject object) throws JSONException {
    IGeometry geom = null;//from  ww w. j a v  a 2 s  .c  om
    LineString[] lineStrings;
    if (object.get("type").equals("MultiLineString")) {
        JSONArray coordinates = object.getJSONArray("coordinates");
        int size = coordinates.length();
        lineStrings = new LineString[size];
        LineString l;
        for (int i = 0; i < size; i++) {
            JSONArray lineStrCoord = coordinates.getJSONArray(i);
            double[][] coords = this.decodeLineStringCoords(lineStrCoord);
            l = new LineString(coords[0], coords[1]);
            lineStrings[i] = l;
        }

        geom = new MultiLineString(lineStrings);
    } else if (object.get("type").equals("LineString")) {
        JSONArray coordinates = object.getJSONArray("coordinates");
        double[][] coords = this.decodeLineStringCoords(coordinates);
        geom = new LineString(coords[0], coords[1]);
    } else if (object.get("type").equals("Point")) {
        JSONArray coordinates = object.getJSONArray("coordinates");
        geom = new Point(coordinates.getDouble(0), coordinates.getDouble(1));
    } else if (object.get("type").equals("Polygon")) {
        JSONArray coordinates = object.getJSONArray("coordinates");
        double[][] coords = this.decodeLineStringCoords(coordinates);
        geom = new Polygon(coords[0], coords[1]);
    }

    return geom;
}