Example usage for org.json JSONObject length

List of usage examples for org.json JSONObject length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of keys stored in the JSONObject.

Usage

From source file:ai.susi.mind.SusiTransfer.java

/**
 * A conclusion from choices is done by the application of a function on the choice set.
 * This may be done by i.e. counting the number of choices or extracting a maximum element.
 * @param choices the given set of json objects from the data object of a SusiThought
 * @returnan array of json objects which are the extraction of given choices according to the given mapping
 *//*from  w ww  . j av a 2s .c  o m*/
public JSONArray conclude(JSONArray choices) {
    JSONArray a = new JSONArray();
    if (this.selectionMapping != null && this.selectionMapping.size() == 1) {
        // test if this has an aggregation key: AVG, COUNT, MAX, MIN, SUM
        final String aggregator = this.selectionMapping.keySet().iterator().next();
        final String aggregator_as = this.selectionMapping.get(aggregator);
        if (aggregator.startsWith("COUNT(") && aggregator.endsWith(")")) { // TODO: there should be a special pattern for this to make it more efficient
            return a.put(new JSONObject().put(aggregator_as, choices.length()));
        }
        if (aggregator.startsWith("MAX(") && aggregator.endsWith(")")) {
            final AtomicDouble max = new AtomicDouble(Double.MIN_VALUE);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> max.set(Math.max(max.get(), ((JSONObject) json).getDouble(c))));
            return a.put(new JSONObject().put(aggregator_as, max.get()));
        }
        if (aggregator.startsWith("MIN(") && aggregator.endsWith(")")) {
            final AtomicDouble min = new AtomicDouble(Double.MAX_VALUE);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> min.set(Math.min(min.get(), ((JSONObject) json).getDouble(c))));
            return a.put(new JSONObject().put(aggregator_as, min.get()));
        }
        if (aggregator.startsWith("SUM(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            return a.put(new JSONObject().put(aggregator_as, sum.get()));
        }
        if (aggregator.startsWith("AVG(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            return a.put(new JSONObject().put(aggregator_as, sum.get() / choices.length()));
        }
    }
    if (this.selectionMapping != null && this.selectionMapping.size() == 2) {
        Iterator<String> ci = this.selectionMapping.keySet().iterator();
        String aggregator = ci.next();
        String column = ci.next();
        if (column.indexOf('(') >= 0) {
            String s = aggregator;
            aggregator = column;
            column = s;
        }
        final String aggregator_as = this.selectionMapping.get(aggregator);
        final String column_as = this.selectionMapping.get(column);
        final String column_final = column;
        if (aggregator.startsWith("PERCENT(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(8, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            choices.forEach(json -> a.put(
                    new JSONObject().put(aggregator_as, 100.0d * ((JSONObject) json).getDouble(c) / sum.get())
                            .put(column_as, ((JSONObject) json).get(column_final))));
            return a;
        }
    }
    // this.selectionMapping == null -> extract everything
    for (Object json : choices) {
        JSONObject extraction = this.extract((JSONObject) json);
        if (extraction.length() > 0)
            a.put(extraction);
    }
    return a;
}

From source file:org.zaizi.alfresco.redlink.service.search.solr.SensefySolrJSONResultSet.java

/**
 * Detached result set based on that provided
 * //from  ww  w . j a  v a  2  s . c o m
 * @param resultSet
 */
@SuppressWarnings("rawtypes")
public SensefySolrJSONResultSet(JSONObject json, SearchParameters searchParameters, NodeService nodeService,
        NodeDAO nodeDao, LimitBy limitBy, int maxResults) {
    // Note all properties are returned as multi-valued from the WildcardField "*" definition in the SOLR schema.xml
    this.nodeService = nodeService;
    this.nodeDao = nodeDao;
    try {
        JSONObject responseHeader = json.getJSONObject("header");
        status = responseHeader.getLong("status");
        queryTime = responseHeader.getLong("qtime");

        JSONObject response = json.getJSONObject("response");
        numberFound = response.getLong("numFound");
        start = response.getLong("start");
        // maxScore = Float.valueOf(response.getString("maxScore"));

        JSONArray docs = response.getJSONArray("docs");

        int numDocs = docs.length();

        ArrayList<Long> rawDbids = new ArrayList<Long>(numDocs);
        ArrayList<Float> rawScores = new ArrayList<Float>(numDocs);
        for (int i = 0; i < numDocs; i++) {
            JSONObject doc = docs.getJSONObject(i);
            Long dbid = doc.getLong("DBID");
            Float score = Float.valueOf(doc.getString("score"));

            rawDbids.add(dbid);
            rawScores.add(score);
        }

        // bulk load

        nodeDao.cacheNodesById(rawDbids);

        // filter out rubbish

        page = new ArrayList<Pair<Long, Float>>(numDocs);
        refs = new ArrayList<NodeRef>(numDocs);
        for (int i = 0; i < numDocs; i++) {
            Long dbid = rawDbids.get(i);
            NodeRef nodeRef = nodeService.getNodeRef(dbid);

            if (nodeRef != null) {
                page.add(new Pair<Long, Float>(dbid, rawScores.get(i)));
                refs.add(nodeRef);
            }
        }

        if (json.has("facets")) {
            JSONObject facets = json.getJSONObject("facets");
            Iterator it = facets.keys();
            while (it.hasNext()) {
                String facetName = (String) it.next();
                JSONObject facetJSON = facets.getJSONObject(facetName);
                ArrayList<Pair<String, Integer>> facetValues = new ArrayList<Pair<String, Integer>>(
                        facetJSON.length());
                Iterator it2 = facetJSON.keys();
                while (it2.hasNext()) {
                    String facetEntryValue = (String) it2.next();
                    int facetEntryCount = facetJSON.getInt(facetEntryValue);
                    Pair<String, Integer> pair = new Pair<String, Integer>(facetEntryValue, facetEntryCount);
                    facetValues.add(pair);
                }
                fieldFacets.put(facetName, facetValues);
            }
        }

    } catch (JSONException e) {

    }
    // We'll say we were unlimited if we got a number less than the limit
    this.resultSetMetaData = new SimpleResultSetMetaData(
            maxResults > 0 && numberFound < maxResults ? LimitBy.UNLIMITED : limitBy,
            PermissionEvaluationMode.EAGER, searchParameters);
}

From source file:com.microsoft.live.unittest.DeleteTest.java

@Override
protected void checkValidResponseBody(LiveOperation operation) {
    JSONObject result = operation.getResult();
    assertEquals(0, result.length());

    String rawResult = operation.getRawResult();
    assertEquals("{}", rawResult);
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static List<Geocache> parseCaches(final JSONObject response) {
    try {/*from   w  w w.j  av a  2  s . c  om*/
        // Check for empty result
        final String result = response.getString("results");
        if (StringUtils.isBlank(result) || StringUtils.equals(result, "[]")) {
            return Collections.emptyList();
        }

        // Get and iterate result list
        final JSONObject cachesResponse = response.getJSONObject("results");
        if (cachesResponse != null) {
            final List<Geocache> caches = new ArrayList<Geocache>(cachesResponse.length());
            @SuppressWarnings("unchecked")
            final Iterator<String> keys = cachesResponse.keys();
            while (keys.hasNext()) {
                final String key = keys.next();
                final Geocache cache = parseSmallCache(cachesResponse.getJSONObject(key));
                caches.add(cache);
            }
            return caches;
        }
    } catch (final JSONException e) {
        Log.e("OkapiClient.parseCachesResult", e);
    }
    return Collections.emptyList();
}

From source file:samples.piggate.com.piggateCompleteExample.Activity_Logged.java

synchronized public void getOffersToExchange() {
    _piggate.RequestGetExchange().setListenerRequest(new Piggate.PiggateCallBack() {
        @Override//w w  w .ja v a2s  .  c o m
        public void onComplete(int statusCode, Header[] headers, String msg, JSONObject data) {
        }

        @Override
        public void onError(int statusCode, Header[] headers, String msg, JSONObject data) {
        }

        @Override
        public void onComplete(int statusCode, Header[] headers, String msg, JSONArray data) {
            exchangeOfferList = new ArrayList<>(); //List of offers to exchange
            for (int i = 0; i < data.length(); i++) {
                try {
                    exchangeOfferList.add(new PiggateOffers(data.getJSONObject(i))); //Get the exchange offer list
                } catch (JSONException e) {
                }
            }

            //Set the left drawer list
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDrawer.removeAllItems();
                    for (int i = 0; i < exchangeOfferList.size(); i++) {
                        mDrawer.addItem(
                                new PrimaryDrawerItem().withName(exchangeOfferList.get(i).getName().toString())
                                        .withDescription(exchangeOfferList.get(i).getDescription().toString()));
                    }
                }
            });
        }

        @Override
        public void onError(int statusCode, Header[] headers, String msg, JSONArray data) {
        }
    }).exec();
}

From source file:org.loklak.harvester.TwitterAPI.java

public static JSONObject getUser(String screen_name, boolean forceReload) throws TwitterException, IOException {
    if (!forceReload) {
        JsonFactory mapcapsule = DAO.user_dump.get("screen_name", screen_name);
        if (mapcapsule == null)
            mapcapsule = DAO.user_dump.get("id_str", screen_name);
        if (mapcapsule != null) {
            JSONObject json = mapcapsule.getJSON();
            if (json.length() > 0) {
                // check if the entry is maybe outdated, i.e. if it is empty or too old
                try {
                    Date d = DAO.user_dump.parseDate(json);
                    if (d.getTime() + DateParser.DAY_MILLIS > System.currentTimeMillis())
                        return json;
                } catch (ParseException e) {
                    return json;
                }/*  w  w w .  ja  va2s .c  o m*/
            }
        }
    }
    TwitterFactory tf = getUserTwitterFactory(screen_name);
    if (tf == null)
        tf = getAppTwitterFactory();
    if (tf == null)
        return new JSONObject();
    Twitter twitter = tf.getInstance();
    User user = twitter.showUser(screen_name);
    RateLimitStatus rateLimitStatus = user.getRateLimitStatus();
    getUserResetTime = System.currentTimeMillis() + rateLimitStatus.getSecondsUntilReset() * 1000;
    getUserRemaining = rateLimitStatus.getRemaining();
    JSONObject json = user2json(user);
    enrichLocation(json);
    DAO.user_dump.putUnique(json);
    return json;
}

From source file:com.hunch.api.HunchNextQuestion.java

public static HunchNextQuestion buildFromJSON(final JSONObject response) {
    final HunchNextQuestion.Builder nqBuilder = getBuilder();

    if (response.has("rankedResultResponses") && response.length() == 1) {
        // this is the last question in the topic
        // it contains only the list of results to be passed
        // to rankedResponses
        try {/*from  w  w w .jav  a  2s .  c o m*/

            nqBuilder.init(response).setRankedResultResponses(response.getString("rankedResultResponses"));
        } catch (JSONException e) {
            throw new RuntimeException("Couldn't build HunchNextQuestion!", e);
        }

        return nqBuilder.buildForResults();
    }

    final HunchQuestion.Builder qBuilder = HunchQuestion.getBuilder();
    final HunchTopic.Builder tBuilder = HunchTopic.getBuilder();
    final HunchResponse.Builder respBuilder = HunchResponse.getBuilder();
    final HunchCategory.Builder catBuilder = HunchCategory.getBuilder();

    try {
        final JSONObject jsonNextQuestion = response.getJSONObject("nextQuestion");

        List<HunchResponse> responses = new ArrayList<HunchResponse>();

        JSONArray jsonResponses = jsonNextQuestion.getJSONArray("responses");

        for (int i = 0; i < jsonResponses.length(); i++) {
            JSONObject jsonResponse = jsonResponses.getJSONObject(i);

            /*
             *    image url can be not set on some             
             *  response objects returned by the Hunch API
             *  --
             *  in order to avoid jumping to the catch block
             *  upon missing imageUrl, we need to handle it
             *  in it's own try block
             */

            String respImgUrl = null;
            try {
                respImgUrl = jsonResponse.getString("imageUrl");
            } catch (JSONException e) {
                Log.v(Const.TAG,
                        "got response object with no imageUrl " + "in HunchNextQuestion.buildFromJSON()");
            }

            /*
             *    Same deal here, the responseID is not set for 
             *  "skip this question" responses, handle it separately
             */

            Integer respID = null;
            try {
                respID = jsonResponse.getInt("responseId");
            } catch (JSONException e) {
                //Log.d( Const.TAG, "couldn't find ID for HunchResponse! (probably a " +
                //      "\"skip this question\" response)" );
            }

            //Log.d( Const.TAG, "building hunchResponse...\n" + jsonResponse.toString( 4 ) );

            respBuilder.init(jsonResponse).setId(respID).setText(jsonResponse.getString("responseText"))
                    .setQAState(jsonResponse.getString("qaState")).setImageUrl(respImgUrl);

            HunchResponse resp = respBuilder.buildForNextQuestion();

            responses.add(resp);
        }

        //Log.d( Const.TAG, "building HunchQuestion...\n" + jsonNextQuestion.toString( 4 ) );

        /*
         * Again, imageUrl can be null sometimes when the
         * API returns a hunchQuestion as part of a
         * nextQuestion call, so we have to handle it 
         * in a separate try block 
         */
        String questionImageUrl = null;
        try {
            questionImageUrl = jsonNextQuestion.getString("imageUrl");
        } catch (JSONException e) {
            Log.v(Const.TAG, "got question object with no imageUrl " + "in HunchNextQuestion.buildFromJSON()");
        }

        // build the question
        qBuilder.init(jsonNextQuestion).setId(jsonNextQuestion.getInt("questionId"))
                .setText(jsonNextQuestion.getString("questionText"))
                .setQuestionNumber(jsonNextQuestion.getInt("questionNumber")).setImageUrl(questionImageUrl)
                .setResponses(responses);

        final HunchQuestion nextQuestion = qBuilder.buildForNextQuestion();

        JSONObject jsonTopic = response.getJSONObject("topic");

        JSONObject jsonCategory = jsonTopic.getJSONObject("category");

        //Log.d( Const.TAG, "building HunchCategory...\n" + jsonCategory.toString( 4 ) );

        catBuilder.init(jsonCategory).setUrlName(jsonCategory.getString("categoryUrlName"))
                .setName(jsonCategory.getString("categoryName"))
                .setImageUrl(jsonCategory.getString("categoryImageUrl"));

        //Log.d( Const.TAG, "building HunchTopic...\n" + jsonTopic.toString( 4 ) );

        tBuilder.init(jsonTopic).setId(jsonTopic.getString("topicId"))
                .setDecision(jsonTopic.getString("topicDecision")).setHunchUrl(jsonTopic.getString("hunchUrl"))
                .setImageUrl(jsonTopic.getString("imageUrl")).setCategory(catBuilder.build());

        final IHunchTopic topic = tBuilder.buildForNextQuestion();

        /*
         * PrevQaState is left unset by the API on the first question.
         * Again, gotta handle it separately.
         */

        String prevQaState = null;
        try {
            prevQaState = response.getString("prevQaState");
        } catch (JSONException e) {
            Log.i(Const.TAG, "got nextQuestion object with no prevQaState "
                    + "in HunchNextQuestion.buildFromJSON() (probably first question)");
        }

        nqBuilder.init(response).setNextQuestion(nextQuestion).setTopic(topic).setPrevQAState(prevQaState)
                .setRankedResultResponses(response.getString("rankedResultResponses"));

    } catch (JSONException e) {
        throw new RuntimeException("Couldn't build HunchNextQuestion!", e);
    }

    return nqBuilder.build();
}

From source file:com.clover.sdk.v3.JsonHelper.java

private static Object deepCopy(Object object) {
    if (object == null) {
        return null;
    } else if (object == JSONObject.NULL) {
        return JSONObject.NULL;
    } else {//from   www.java2  s . c  o  m
        Class<?> c = object.getClass();
        if (c == JSONObject.class) {
            JSONObject src = ((JSONObject) object);
            JSONObject dst = new JSONObject();

            Iterator<String> srcKeys = src.keys();
            while (srcKeys.hasNext()) {
                String srcKey = srcKeys.next();
                try {
                    dst.put(srcKey, deepCopy(src.get(srcKey)));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            return dst;
        } else if (c == JSONArray.class) {
            JSONArray src = ((JSONArray) object);
            JSONArray dst = new JSONArray();

            for (int i = 0, count = src.length(); i < count; i++) {
                try {
                    dst.put(deepCopy(src.get(i)));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            return dst;
        } else {
            if (c == String.class || c == Long.class || c == Boolean.class || c == Integer.class
                    || c == Double.class || c == Float.class) {
                return object;
            } else {
                throw new RuntimeException("Unsupported object type: " + c.getSimpleName());
            }
        }

    }
}

From source file:com.android.i18n.addressinput.JsoMap.java

/**
 * Retrieve the JsoMap object for specified key.
 *
 * @param key key name./*from  www .j  a  v  a2s.com*/
 * @return JsoMap object.
 * @throws ClassCastException, IllegalArgumentException.
 */
@SuppressWarnings("unchecked")
// JSONObject.keys() has no type information.
JsoMap getObj(String key) throws ClassCastException, IllegalArgumentException {
    try {
        Object o = super.get(key);
        if (o instanceof JSONObject) {
            JSONObject value = (JSONObject) o;
            ArrayList<String> keys = new ArrayList<String>(value.length());
            for (Iterator<String> it = value.keys(); it.hasNext();) {
                keys.add(it.next());
            }
            String[] names = new String[keys.size()];
            return new JsoMap(value, keys.toArray(names));
        } else if (o instanceof Integer) {
            throw new IllegalArgumentException();
        } else {
            throw new ClassCastException();
        }
    } catch (JSONException e) {
        return null;
    }
}

From source file:com.scvngr.levelup.core.net.request.factory.CreditCardRequestFactoryTest.java

/**
 * Tests//from w  w w.j  a v a 2  s .c o  m
 * {@link com.scvngr.levelup.core.net.request.factory.CreditCardRequestFactory#buildCreateCardRequest(String, String, String, String, String)}
 * .
 *
 * @throws com.scvngr.levelup.core.net.AbstractRequest.BadRequestException if the request throws
 * @throws org.json.JSONException
 */
@SmallTest
public void testBuildCreateCardRequest() throws BadRequestException, JSONException {
    final CreditCardRequestFactory builder = new CreditCardRequestFactory(getContext(),
            new MockAccessTokenRetriever());
    final AbstractRequest request = builder.buildCreateCardRequest("card_number", "cvv", "01", "1999", "00000");

    final LevelUpRequest apiRequest = (LevelUpRequest) request;

    final JSONObject params = new JSONObject(apiRequest.getBody(getContext()));

    assertEquals(1, params.length());

    final JSONObject creditCard = params.getJSONObject("credit_card");

    assertEquals(HttpMethod.POST, request.getMethod());
    assertTrue("hits credit_cards endpoint",
            request.getUrl(mContext).getPath().endsWith(EXPECTED_CREDIT_CARDS_ENDPOINT));
    assertTrue("Url points to proper api version",
            request.getUrl(getContext()).getPath().contains(LevelUpRequest.API_VERSION_CODE_V15));

    /*
     * assertFalse is used because the request parameters are encrypted, so they *shouldn't* be
     * the values we entered.
     */
    assertFalse("card_number".equals(creditCard.getString("encrypted_number")));
    assertFalse("cvv".equals(creditCard.getString("encrypted_cvv")));
    assertFalse("01".equals(creditCard.getString("encrypted_expiration_month")));
    assertFalse("1999".equals(creditCard.getString("encrypted_expiration_year")));
    assertEquals("00000", creditCard.getString("postal_code"));
}