Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:com.hueemulator.lighting.utils.TestUtils.java

@SuppressWarnings("unchecked")
private static Object convertJsonElement(Object elem) throws JSONException {
    if (elem instanceof JSONObject) {
        JSONObject obj = (JSONObject) elem;
        Iterator<String> keys = obj.keys();
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        while (keys.hasNext()) {
            String key = keys.next();
            jsonMap.put(key, convertJsonElement(obj.get(key)));
        }//  w w  w  .j a v a2s.co m
        return jsonMap;
    } else if (elem instanceof JSONArray) {
        JSONArray arr = (JSONArray) elem;
        Set<Object> jsonSet = new HashSet<Object>();
        for (int i = 0; i < arr.length(); i++) {
            jsonSet.add(convertJsonElement(arr.get(i)));
        }
        return jsonSet;
    } else {
        return elem;
    }
}

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

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

    if (SFparkActivity.responseString == null || SFparkActivity.responseString == "") {
        return;//from w  w w. j  a  v a  2 s .  c o m
    }

    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()));
                                    }/*from w  ww. j a  v  a  2 s.  com*/
                                }

                        );

                        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:org.acaro.graffiti.processing.GraffitiReader.java

@Override
public BasicVertex<Text, IntWritable, Text, Message> getCurrentVertex()
        throws IOException, InterruptedException {

    Vertex vertex = new Vertex();
    Text line = getRecordReader().getCurrentValue();

    try {/*  w ww  .  j  a v a2 s .  co  m*/

        JSONArray jsonVertex = new JSONArray(line.toString());
        vertex.setVertexId(new Text(jsonVertex.getString(0)));
        vertex.setMsgList(msgList);
        JSONArray jsonEdgeArray = jsonVertex.getJSONArray(1);

        for (int i = 0; i < jsonEdgeArray.length(); ++i) {
            JSONArray jsonEdge = jsonEdgeArray.getJSONArray(i);
            vertex.addEdge(new Text(jsonEdge.getString(1)), new Text(jsonEdge.getString(0)));
        }
    } catch (JSONException e) {
        throw new IllegalArgumentException("next: Couldn't get vertex from line " + line, e);
    }

    return vertex;
}

From source file:org.catnut.fragment.ConversationFragment.java

@Override
protected void refresh() {
    // ???/*from   w w w . j  a v  a 2  s.co  m*/
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    final int size = getFetchSize();
    (new Thread(new Runnable() {
        @Override
        public void run() {
            // ??????(?-)???Orz...
            String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, null, Comment.TABLE, null,
                    BaseColumns._ID + " desc", size + ", 1" // limit x, y
            );
            Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE),
                    null, query, null, null);
            // the cursor never null?
            final long since_id;
            if (cursor.moveToNext()) {
                since_id = cursor.getLong(0);
            } else {
                since_id = 0;
            }
            cursor.close();
            final CatnutAPI api = CommentsAPI.to_me(since_id, 0, getFetchSize(), 0, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.Comments2MeProcessor(), new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(TOTAL_NUMBER);
                                    // ???
                                    JSONArray jsonArray = response.optJSONArray(Comment.MULTIPLE);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, ConversationFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

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

/**
 * Make remote request to get all loyalty cards stored in Cozy
 */// w  w w .  ja va2s .c  om
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   w w w . java2s  .  c o  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 {//from   ww  w. jav  a  2  s.c om
        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 {/* w w  w .  j a  va 2s . 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;
}