Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray getJSONObject.

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:ru.neverdark.phototools.utils.Geocoder.java

/**
 * Gets coordinate from location name//from  w  w w.  j  a va 2s.  com
 * 
 * @param searchString
 *            user specify location name
 * @return coordinates for founded location or null if not found
 */
public LatLng getFromLocation(String searchString) {
    LatLng coords = null;
    String locationInfo = getLocationInfo(searchString);

    if (locationInfo.length() > 0) {
        try {
            JSONObject jsonObject = new JSONObject(locationInfo);
            JSONArray jsonArray = (JSONArray) jsonObject.get("results");
            JSONObject jsonLocation = jsonArray.getJSONObject(0).getJSONObject("geometry")
                    .getJSONObject("location");
            Double longitude = jsonLocation.getDouble("lng");
            Double latitude = jsonLocation.getDouble("lat");

            coords = new LatLng(latitude, longitude);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return coords;
}

From source file:com.example.android.popularmoviesist2.data.FetchTrailerMovieTask.java

private String[] getMoviesDataFromJson(String moviesJsonStr) throws JSONException {

    final String JSON_LIST = "results";
    final String JSON_ID = "id";
    final String JSON_KEY = "key";
    final String JSON_NAME = "name";
    final String JSON_SITE = "site";

    urlYoutbe.clear();//from   w w  w .ja  va 2 s. c om

    try {
        JSONObject moviesJson = new JSONObject(moviesJsonStr);
        JSONArray moviesArray = moviesJson.getJSONArray(JSON_LIST);

        final String[] result = new String[moviesArray.length()];

        for (int i = 0; i < moviesArray.length(); i++) {

            JSONObject movie = moviesArray.getJSONObject(i);
            String id = movie.getString(JSON_ID);
            String key = movie.getString(JSON_KEY);
            String name = movie.getString(JSON_NAME);
            String site = movie.getString(JSON_SITE);

            result[i] = key;
        }
        return result;
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
        return null;
    }

}

From source file:gov.sfmta.sfpark.MainScreenActivity.java

public void readData() throws JSONException {
    MYLOG("readData() start");

    if (SFparkActivity.responseString == null || SFparkActivity.responseString == "") {
        return;//from ww  w . java  2  s.com
    }

    String message = null;
    JSONObject rootObject = null;
    JSONArray jsonAVL = null;

    rootObject = new JSONObject(SFparkActivity.responseString);
    message = rootObject.getString("MESSAGE");
    jsonAVL = rootObject.getJSONArray("AVL");
    timeStampXML = rootObject.getString("AVAILABILITY_UPDATED_TIMESTAMP");

    MYLOG(message);

    int i = 0;
    int len = jsonAVL.length();

    if (annotations == null) {
        annotations = new ArrayList<MyAnnotation>();
    } else {
        annotations.clear();
    }

    for (i = 0; i < len; ++i) {
        JSONObject interestArea = jsonAVL.getJSONObject(i);
        MyAnnotation annotation = new MyAnnotation();
        annotation.allGarageData = interestArea;
        annotation.initFromData();

        // new: UBER-HACK! SFMTA wants me to hide the Calif/Steiner lot.
        if ("California and Steiner Lot".equals(annotation.title))
            continue;

        annotations.add(annotation);
    }

    MYLOG("readData() finish ");
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache)
        throws JSONException, IOException {
    String uniqueID = null;/*from  w w w .j  av a2 s  .c  o m*/
    List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>();
    List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>();
    Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>();
    JSONArray jsonAnnot = new JSONArray();
    final String SEP = "::";

    // assertions: these always supply a term
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI));
        obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest)));
        obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI));
        jsonAnnot.put(obj);

        String hash = asrt.propURI + SEP + asrt.valueURI + SEP
                + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest));
        gotAnnot.add(hash);
    }

    // go through the columns one at a time
    for (String key : keydata.keySet()) {
        String data = keydata.getString(key);

        Identifier id = findIdentifier(key);
        if (id != null) {
            if (uniqueID == null)
                uniqueID = id.prefix + data;
            continue;
        }

        TextBlock tblk = findTextBlock(key);
        if (tblk != null) {
            if (Util.isBlank(tblk.title))
                linesTitle.add(data);
            else
                linesBlock.add(tblk.title + ": " + data);
        }

        Value val = findValue(key, data);
        if (val != null) {
            if (Util.isBlank(val.valueURI)) {
                linesSkipped.add(key + ": " + data);
            } else {
                String hash = val.propURI + SEP + val.valueURI + SEP
                        + (val.groupNest == null ? "" : String.join(SEP, val.groupNest));
                if (gotAnnot.contains(hash))
                    continue;

                JSONObject obj = new JSONObject();
                obj.put("propURI", ModelSchema.expandPrefix(val.propURI));
                obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest)));
                obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI));
                jsonAnnot.put(obj);
                gotAnnot.add(hash);
                linesProcessed.add(key + ": " + data);
            }
            continue;
        }

        Literal lit = findLiteral(key, data);
        if (lit != null) {
            String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest))
                    + SEP + data;
            if (gotLiteral.contains(hash))
                continue;

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(lit.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest)));
            obj.put("valueLabel", data);
            jsonAnnot.put(obj);
            gotLiteral.add(hash);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        Reference ref = findReference(key, data);
        if (ref != null) {
            Pattern ptn = Pattern.compile(ref.valueRegex);
            Matcher m = ptn.matcher(data);
            if (!m.matches() || m.groupCount() < 1)
                throw new IOException(
                        "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group.");

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(ref.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest)));
            obj.put("valueLabel", ref.prefix + m.group(1));
            jsonAnnot.put(obj);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        // probably shouldn't get this far, but just in case
        linesSkipped.add(key + ": " + data);
    }

    // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes
    for (int n = 0; n < jsonAnnot.length(); n++) {
        JSONObject obj = jsonAnnot.getJSONObject(n);
        String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI");
        if (valueURI == null)
            continue;
        String[] groupNest = obj.getJSONArray("groupNest").toStringArray();
        Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI),
                groupNest);
        if (assnList.length == 0)
            continue;
        SchemaTree tree = treeCache.get(assnList[0]);
        if (tree == null)
            continue;

        Set<String> exclusion = new HashSet<>();
        for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent)
            exclusion.add(node.uri);
        if (exclusion.size() == 0)
            continue;

        for (int i = jsonAnnot.length() - 1; i >= 0; i--)
            if (i != n) {
                obj = jsonAnnot.getJSONObject(i);
                if (!obj.has("valueURI"))
                    continue;
                if (!propURI.equals(obj.getString("propURI")))
                    continue;
                if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray()))
                    continue;
                if (!exclusion.contains(obj.getString("valueURI")))
                    continue;
                jsonAnnot.remove(i);
            }
    }

    /*String text = "";
    if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n";
    if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n";
    text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/

    List<String> sections = new ArrayList<>();
    if (linesTitle.size() > 0)
        sections.add(String.join(" / ", linesTitle));
    if (linesBlock.size() > 0)
        sections.add(String.join("\n", linesBlock));
    sections.add("#### IMPORTED ####");
    if (linesSkipped.size() > 0)
        sections.add("SKIPPED:\n" + String.join("\n", linesSkipped));
    if (linesProcessed.size() > 0)
        sections.add("PROCESSED:\n" + String.join("\n", linesProcessed));
    String text = String.join("\n\n", sections);

    JSONObject assay = new JSONObject();
    assay.put("uniqueID", uniqueID);
    assay.put("text", text);
    assay.put("schemaURI", schema.getSchemaPrefix());
    assay.put("annotations", jsonAnnot);
    return assay;
}

From source file:ai.ilikeplaces.logic.sits9.SubscriberNotifications.java

@Timeout
synchronized public void timeout(final Timer timer)
        throws IOException, SAXException, TransformerException, JSONException, SQLException {

    final HBaseCrudService<GeohashSubscriber> _geohashSubscriberHBaseCrudService = new HBaseCrudService<GeohashSubscriber>();
    final HBaseCrudService<GeohashSubscriber>.Scanner _scanner = _geohashSubscriberHBaseCrudService
            .scan(new GeohashSubscriber(), 1).returnValueBadly();

    while (_scanner.getNewValue() != null) {
        final String _newValue = _scanner.getNewValue();
        Loggers.debug("Scanned value:" + _newValue);
        final RowResponse _rowResponse = new Gson().fromJson(_newValue, RowResponse.class);
        Loggers.debug("Scanned as GSON:" + _rowResponse.toString());

        for (final Row _row : _rowResponse.Row) {

            final BASE64Decoder _base64DecoderRowKey = new BASE64Decoder();
            final byte[] _bytes = _base64DecoderRowKey.decodeBuffer(_row.key);
            final String rowKey = new String(_bytes);
            Loggers.debug("Decoded row key:" + rowKey);

            for (final Cell _cell : _row.Cell) {
                final BASE64Decoder _base64DecoderValue = new BASE64Decoder();
                final byte[] _valueBytes = _base64DecoderValue.decodeBuffer(_cell.$);
                final String _cellAsString = new String(_valueBytes);
                Loggers.debug("Cell as string:" + _cellAsString);
                final GeohashSubscriber _geohashSubscriber = new GeohashSubscriber();

                final DatumReader<GeohashSubscriber> _geohashSubscriberSpecificDatumReader = new SpecificDatumReader<GeohashSubscriber>(
                        _geohashSubscriber.getSchema());
                final BinaryDecoder _binaryDecoder = DecoderFactory.get().binaryDecoder(_valueBytes, null);
                final GeohashSubscriber _read = _geohashSubscriberSpecificDatumReader.read(_geohashSubscriber,
                        _binaryDecoder);
                Loggers.debug("Decoded value avro:" + _read.toString());

                final Date now = new Date();
                final Calendar _week = Calendar.getInstance();
                _week.setTimeInMillis(now.getTime() + (7 * 24 * 60 * 60 * 1000));
                final SimpleDateFormat _simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                _simpleDateFormat.format(_week.getTime());

                final StringBuffer eventList = new StringBuffer("");

                {//Eventful

                    try {

                        final SimpleDateFormat eventfulDate = new SimpleDateFormat("yyyyMMdd00");
                        _simpleDateFormat.format(_week.getTime());

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("http://api.eventful.com/json/events/search/")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("location", "" + _read.getLatitude() + "," + _read.getLongitude());
                                        put("within", "" + 100);
                                        put("date", eventfulDate.format(Calendar.getInstance().getTime()) + "-"
                                                + eventfulDate.format(_week.getTime()));
                                    }/* w ww .j a  va  2s  .  c o  m*/
                                }

                        );

                        Loggers.debug("Eventful Reply:" + jsonObject.toString());

                        final JSONArray events = jsonObject.getJSONObject("events").getJSONArray("event");

                        final Document eventTemplateDocument = HTMLDocParser
                                .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL_EVENT);
                        final String eventTemplate = HTMLDocParser
                                .convertNodeToHtml(HTMLDocParser.$("content", eventTemplateDocument));

                        for (int i = 0; i < events.length(); i++) {
                            final JSONObject eventJSONObject = new JSONObject(events.get(i).toString());
                            Double.parseDouble(eventJSONObject.getString(LATITUDE));
                            Double.parseDouble(eventJSONObject.getString(LONGITUDE));
                            final String eventName = eventJSONObject.getString("title");
                            final String eventUrl = eventJSONObject.getString("url");
                            final String eventDate = eventJSONObject.getString("start_time");
                            final String eventVenue = eventJSONObject.getString("venue_name");
                            Loggers.debug("Event name:" + eventName);
                            eventList
                                    .append(eventTemplate
                                            .replace("_name_link_",
                                                    !(("" + eventUrl).isEmpty()) ? eventUrl
                                                            : ("https://www.google.com/search?q=" + eventName
                                                                    .replaceAll(" ", "+").replaceAll("-", "+")))
                                            .replace("_place_link_",
                                                    "https://maps.googleapis.com/maps/api/staticmap?sensor=false&size=600x600&markers=color:blue%7Clabel:S%7C"
                                                            + _read.getLatitude().toString() + ","
                                                            + _read.getLongitude().toString())
                                            .replace("_name_", eventName).replace("_place_", eventVenue)
                                            .replace("_date_", eventDate));
                        }
                    } catch (final Throwable t) {
                        Loggers.error("Error appending Eventful data to Geohash Subscriber", t);
                    }
                }

                {//Foursquare

                    try {

                        _simpleDateFormat.format(_week.getTime());

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("https://api.foursquare.com/v2/venues/explore")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("ll", "" + _read.getLatitude() + "," + _read.getLongitude());
                                        put("radius", "" + 50000);//meters
                                        put("intent", "browse");
                                        put("section", "topPicks");
                                        put("client_secret",
                                                "PODRX5YWBSLAKAYRQ5CLPEPS3WHCXWFIJ3LXF3AKH4U1BDNI");
                                        put("client_id", "25JZAK3TQPLIPUUXPIJWXQ5NSKSPTP4SYZLUZSCTZF3UJ4YX");
                                    }
                                }

                        );

                        Loggers.debug("Foursquare Reply:" + jsonObject.toString());

                        final JSONArray referralArray = jsonObject.getJSONObject("response")
                                .getJSONArray("groups").getJSONObject(0).getJSONArray("items");

                        final Document eventTemplateDocument = HTMLDocParser
                                .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL_PLACE);
                        final String eventTemplate = HTMLDocParser
                                .convertNodeToHtml(HTMLDocParser.$("content", eventTemplateDocument));

                        for (int i = 0; i < referralArray.length(); i++) {

                            final JSONObject referral = referralArray.getJSONObject(i);
                            referral.getJSONObject("venue").getJSONObject("location").getDouble("lng");
                            referral.getJSONObject("venue").getJSONObject("location").getDouble("lat");
                            final String eventName = referral.getJSONObject("venue").getString("name");
                            final String eventUrl = referral.getJSONObject("venue").optString("url");
                            final String eventVenue = referral.getJSONObject("venue").getJSONObject("location")
                                    .getString("address");
                            Loggers.debug("Event name:" + eventName);
                            eventList
                                    .append(eventTemplate
                                            .replace("_name_link_",
                                                    !(("" + eventUrl).isEmpty()) ? eventUrl
                                                            : ("https://www.google.com/search?q=" + eventName
                                                                    .replaceAll(" ", "+").replaceAll("-", "+")))
                                            .replace("_place_link_",
                                                    "https://maps.googleapis.com/maps/api/staticmap?sensor=false&size=600x600&markers=color:blue%7Clabel:S%7C"
                                                            + _read.getLatitude().toString() + ","
                                                            + _read.getLongitude().toString())
                                            .replace("_name_", eventName).replace("_place_", eventVenue)
                                            .replace("_date_", eventName));
                        }
                    } catch (final Throwable t) {
                        Loggers.error("Error appending Foursquare data to Geohash Subscriber", t);
                    }
                }

                final String template = HTMLDocParser
                        .getDocumentAsString(RBGet.getGlobalConfigKey("PAGEFILES") + EMAIL_FRAME);
                final Document email = HTMLDocParser
                        .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL);
                final String _content = HTMLDocParser.convertNodeToHtml(HTMLDocParser.$("content", email));
                final Parameter _unsubscribeLink = new Parameter("http://www.ilikeplaces.com/unsubscribe/")
                        .append(Unsubscribe.TYPE, Unsubscribe.Type.GeohashSubscribe.name(), true)
                        .append(Unsubscribe.VALUE, rowKey);
                final String finalEmail = template.replace("_FrameContent_",
                        _content.replace(" ___||_", eventList.toString()).replace("_unsubscribe_link_",
                                _unsubscribeLink.get()));
                Loggers.debug("Final email:" + finalEmail);
                sendMailLocal.sendAsHTML(_read.getEmailId().toString(), "Thank God it's Friday!", finalEmail);
            }

        }

        _geohashSubscriberHBaseCrudService.scan(new GeohashSubscriber(), _scanner);
    }

    Loggers.debug("Completed scanner");

}

From source file:com.liferay.mobile.android.v62.announcementsentry.AnnouncementsEntryService.java

public JSONObject addEntry(long plid, long classNameId, long classPK, String title, String content, String url,
        String type, int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour,
        int displayDateMinute, int expirationDateMonth, int expirationDateDay, int expirationDateYear,
        int expirationDateHour, int expirationDateMinute, int priority, boolean alert) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*w w w  .  j  a v a 2  s. co  m*/
        JSONObject _params = new JSONObject();

        _params.put("plid", plid);
        _params.put("classNameId", classNameId);
        _params.put("classPK", classPK);
        _params.put("title", checkNull(title));
        _params.put("content", checkNull(content));
        _params.put("url", checkNull(url));
        _params.put("type", checkNull(type));
        _params.put("displayDateMonth", displayDateMonth);
        _params.put("displayDateDay", displayDateDay);
        _params.put("displayDateYear", displayDateYear);
        _params.put("displayDateHour", displayDateHour);
        _params.put("displayDateMinute", displayDateMinute);
        _params.put("expirationDateMonth", expirationDateMonth);
        _params.put("expirationDateDay", expirationDateDay);
        _params.put("expirationDateYear", expirationDateYear);
        _params.put("expirationDateHour", expirationDateHour);
        _params.put("expirationDateMinute", expirationDateMinute);
        _params.put("priority", priority);
        _params.put("alert", alert);

        _command.put("/announcementsentry/add-entry", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *///from w  w  w.  java 2 s  . c o  m
public String getRemoteLoyaltyCards() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                LoyaltyCard.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE,
                                "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        LoyaltyCard loyaltyCard = LoyaltyCard
                                .getByRemoteId(loyaltyCardJson.get("_id").toString());
                        if (loyaltyCard == null) {
                            loyaltyCard = new LoyaltyCard(loyaltyCardJson);
                        } else {
                            loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id"));
                            loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue"));
                            loyaltyCard.setCode(loyaltyCardJson.getInt("code"));
                            loyaltyCard.setLabel(loyaltyCardJson.getString("label"));
                            loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate"));
                        }

                        loyaltyCard.save();
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:org.vaadin.addons.locationtextfield.OpenStreetMapGeocoder.java

protected Collection<GeocodedLocation> createLocations(String address, String input) throws GeocodingException {
    final Set<GeocodedLocation> locations = new LinkedHashSet<GeocodedLocation>();
    try {/*from ww w  .jav  a2  s. co  m*/
        JSONArray results = new JSONArray(input);
        boolean ambiguous = results.length() > 1;
        for (int i = 0; i < results.length(); i++) {
            JSONObject result = results.getJSONObject(i);
            GeocodedLocation loc = new GeocodedLocation();
            loc.setAmbiguous(ambiguous);
            loc.setOriginalAddress(address);
            loc.setGeocodedAddress(result.getString("display_name"));
            loc.setLat(Double.parseDouble(result.getString("lat")));
            loc.setLon(Double.parseDouble(result.getString("lon")));
            loc.setType(getLocationType(result));
            if (result.has("address")) {
                JSONObject obj = result.getJSONObject("address");
                if (obj.has("house_number"))
                    loc.setStreetNumber(obj.getString("house_number"));
                if (obj.has("road"))
                    loc.setRoute(obj.getString("road"));
                if (obj.has("city"))
                    loc.setLocality(obj.getString("city"));
                if (obj.has("county"))
                    loc.setAdministrativeAreaLevel2(obj.getString("county"));
                if (obj.has("state"))
                    loc.setAdministrativeAreaLevel1(obj.getString("state"));
                if (obj.has("postcode"))
                    loc.setPostalCode(obj.getString("postcode"));
                if (obj.has("country_code"))
                    loc.setCountry(obj.getString("country_code").toUpperCase());
            }
            locations.add(loc);
        }
    } catch (JSONException e) {
        throw new GeocodingException(e.getMessage(), e);
    }
    return locations;
}

From source file:com.sudhirkhanger.andpress.rest.WordPressAsyncTask.java

private ArrayList<Post> jsonConvertor(String postJsonStr) {
    ArrayList<Post> postArrayList = new ArrayList<>();

    try {//www .ja va  2 s .co  m
        JSONArray baseJsonArray = new JSONArray(postJsonStr);
        int numberOfItems = baseJsonArray.length();

        for (int i = 0; i < numberOfItems; i++) {
            JSONObject item = baseJsonArray.getJSONObject(i);

            int id = item.optInt(ID);

            JSONObject titleObject = item.getJSONObject(TITLE);
            String title = titleObject.optString(RENDERED);

            JSONObject contentObject = item.getJSONObject(CONTENT);
            String content = contentObject.optString(RENDERED);

            String featured_media = item.optString(FEATURED_MEDIA);

            Post post = new Post(id, title, featured_media, content);
            postArrayList.add(post);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Problem parsing the WordPress JSON results", e);
    }
    return postArrayList;
}

From source file:com.ibm.iot.auto.bluemix.samples.ui.InputData.java

public List<CarProbe> getCarProbes() throws IOException, JSONException {
    List<CarProbe> carProbes = new ArrayList<CarProbe>();

    FileReader fileReader = null;
    try {// www.  j  a va 2 s.c  o  m
        fileReader = new FileReader(inputFile);
        JSONTokener jsonTokener = new JSONTokener(fileReader);
        JSONArray cars = new JSONArray(jsonTokener);
        for (int i = 0; i < cars.length(); i++) {
            JSONObject car = cars.getJSONObject(i);
            CarProbe carProbe = new CarProbe(car.getString("trip_id"), car.getString("timestamp"),
                    car.getDouble("heading"), car.getDouble("speed"), car.getDouble("longitude"),
                    car.getDouble("latitude"));
            carProbes.add(carProbe);
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
    }
    Collections.sort(carProbes);

    return carProbes;
}