Example usage for org.json JSONObject names

List of usage examples for org.json JSONObject names

Introduction

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

Prototype

public JSONArray names() 

Source Link

Document

Produce a JSONArray containing the names of the elements of this JSONObject.

Usage

From source file:com.qbcps.sifterclient.SifterReader.java

/** check if SifterAPI returned error
 * {"error":"Invalid Account","detail":"Please correct the account subdomain."}
* {"error":"Invalid Token","detail":"Please make sure that you are using the correct token."} */
private boolean getSifterError(JSONObject sifterJSONObject) {
    try {/*from   ww  w .ja v  a  2s .  c  om*/
        JSONArray sifterJSONObjFieldNames = sifterJSONObject.names();
        int numKeys = sifterJSONObjFieldNames.length();
        if (numKeys == 2 && LOGIN_ERROR.equals(sifterJSONObjFieldNames.getString(0))
                && LOGIN_DETAIL.equals(sifterJSONObjFieldNames.getString(1))) {
            mLoginError = sifterJSONObject;
            return true;
        }
        mLoginError.put(LOGIN_ERROR, getResources().getString(R.string.token_accepted));
        mLoginError.put(LOGIN_DETAIL, getResources().getString(R.string.token_accepted_msg));
        return false;
    } catch (NotFoundException e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString()); // return true below
    } catch (JSONException e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString()); // return true below
    }
    return true;
}

From source file:edu.wpi.margrave.SQSReader.java

protected static Formula handleStatementCondition(JSONObject obj, Formula theCondition, MVocab vocab)
        throws JSONException, MGEBadIdentifierName, MGEUnknownIdentifier, MGEManagerException {
    // Condition block is a conjunctive list of conditions. all must apply.
    // Each condition is a conjunctive list of value sets. 
    // Each value set is a disjunctive list of values
    // Keys in the condition block are functions to apply
    // Keys in a condition are attribute names. Values are values.

    // Condition block
    //    Function : {}
    //    Function : {}
    // ...//from  ww w  . j a va  2 s  . com

    JSONArray conditionNames = obj.names();
    for (int iCondition = 0; iCondition < conditionNames.length(); iCondition++) {
        String cFunction = (String) conditionNames.get(iCondition);
        JSONObject condition = (JSONObject) obj.get(cFunction);
        //MEnvironment.errorStream.println(cFunction + ": "+condition);

        // condition is a key:value pair or multiple such pairs. The value may be an array.
        // Each sub-condition must be met.
        HashSet<Formula> thisCondition = new HashSet<Formula>();

        JSONArray subConditionNames = condition.names();
        for (int iSubCondition = 0; iSubCondition < subConditionNames.length(); iSubCondition++) {
            String cSubKey = (String) subConditionNames.get(iSubCondition);
            Object subcondition = condition.get(cSubKey);

            // Subcondition: is it an array or a single value?
            if (subcondition instanceof JSONArray) {
                JSONArray subarr = (JSONArray) subcondition;
                HashSet<Formula> valuedisj = new HashSet<Formula>();
                for (int iValue = 0; iValue < subarr.length(); iValue++) {
                    //MEnvironment.errorStream.println(cFunction+"("+cSubKey+", "+subarr.get(iValue)+")");
                    Formula theatom = makeSQSAtom(vocab, "c", "Condition",
                            cFunction + "<" + cSubKey + "><" + subarr.get(iValue) + ">");
                    valuedisj.add(theatom);
                }

                thisCondition.add(MFormulaManager.makeDisjunction(valuedisj));
            } else {
                //MEnvironment.errorStream.println(cFunction+"("+cSubKey+", "+subcondition+")");   
                Formula theatom = makeSQSAtom(vocab, "c", "Condition",
                        cFunction + "<" + cSubKey + "><" + subcondition + ">");
                thisCondition.add(theatom);
            }

        }

        theCondition = MFormulaManager.makeAnd(theCondition, MFormulaManager.makeConjunction(thisCondition));
    }

    return theCondition;
}

From source file:edu.wpi.margrave.SQSReader.java

protected static Formula handleStatementPAR(Object obj, String varname, String parentsortname,
        Formula theTarget, MVocab vocab, String prepend) throws MGEUnsupportedSQS, JSONException,
        MGEBadIdentifierName, MGEUnknownIdentifier, MGEManagerException {
    // obj may be a JSONObject (Principal examples)
    //   with a child with a value OR array of values

    //"Principal": {
    //"AWS": "*"//from  w ww  . ja  v  a2  s  .  c  om
    //}

    //"Principal": {
    //"AWS": ["123456789012","555566667777"]
    //}

    // may also be a simple value (Action example)
    // or an array of values (Resource examples)

    // "Action": ["SQS:SendMessage","SQS:ReceiveMessage"],
    // "Resource": "/987654321098/queue1"

    // TODO: the example principal from "Element Descriptions" doesn't parse...
    //"Principal":[
    //             "AWS": "123456789012",
    //             "AWS": "999999999999"
    //          ]
    // is this just a bad example?

    // *****************************
    // Step 1: Is this a JSONObject? If so, it should have only one key. Prepend that key
    // to all predicate names produced by its value.
    if (obj instanceof JSONObject) {
        JSONObject jobj = (JSONObject) obj;
        JSONArray names = jobj.names();
        if (names.length() != 1)
            throw new MGEUnsupportedSQS("Number of keys != 1 as expected: " + obj.toString());

        Object inner = jobj.get((String) names.get(0));
        return handleStatementPAR(inner, varname, parentsortname, theTarget, vocab,
                prepend + MEnvironment.sIDBSeparator + names.get(0));
    }

    // Now if obj is a simple value, we have a predicate name.
    // If it is an array of length n, we have n predicate names.      
    if (obj instanceof JSONArray) {
        JSONArray jarr = (JSONArray) obj;
        HashSet<Formula> possibleValues = new HashSet<Formula>();

        for (int ii = 0; ii < jarr.length(); ii++) {
            //MEnvironment.errorStream.println(prepend+"="+jarr.get(ii));

            Formula theatom = makeSQSAtom(vocab, varname, parentsortname, prepend + "=" + jarr.get(ii));
            possibleValues.add(theatom);

        }

        theTarget = MFormulaManager.makeAnd(theTarget, MFormulaManager.makeDisjunction(possibleValues));

    } else {
        Formula theatom = makeSQSAtom(vocab, varname, parentsortname, prepend + "=" + obj);
        theTarget = MFormulaManager.makeAnd(theTarget, theatom);
    }

    return theTarget;
}

From source file:com.BreakingBytes.SifterReader.SifterReader.java

private String getFilterSlug() {
    String projDetailURL = new String();
    int issuesPerPage = IssuesActivity.MAX_PER_PAGE;
    JSONArray status = new JSONArray();
    JSONArray priority = new JSONArray();
    int numStatuses;
    int numPriorities;
    boolean[] filterStatus;
    boolean[] filterPriority;
    try {//from ww  w . j ava 2  s .c o m
        JSONObject filters = mSifterHelper.getFiltersFile();
        if (filters.length() == 0)
            return new String();
        issuesPerPage = filters.getInt(IssuesActivity.PER_PAGE);
        status = filters.getJSONArray(IssuesActivity.STATUS);
        priority = filters.getJSONArray(IssuesActivity.PRIORITY);
        numStatuses = status.length();
        numPriorities = priority.length();
        filterStatus = new boolean[numStatuses];
        filterPriority = new boolean[numPriorities];
        for (int i = 0; i < numStatuses; i++)
            filterStatus[i] = status.getBoolean(i);
        for (int i = 0; i < numPriorities; i++)
            filterPriority[i] = priority.getBoolean(i);
    } catch (Exception e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return new String();
    }
    projDetailURL = "?" + IssuesActivity.PER_PAGE + "=" + issuesPerPage;
    projDetailURL += "&" + IssuesActivity.GOTO_PAGE + "=1";
    JSONObject statuses = new JSONObject();
    JSONObject priorities = new JSONObject();
    JSONArray statusNames = new JSONArray();
    JSONArray priorityNames = new JSONArray();
    try {
        JSONObject sifterJSONObject = mSifterHelper.getSifterFilters();
        statuses = sifterJSONObject.getJSONObject(IssuesActivity.STATUSES);
        priorities = sifterJSONObject.getJSONObject(IssuesActivity.PRIORITIES);
        statusNames = statuses.names();
        priorityNames = priorities.names();
    } catch (Exception e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return new String();
    }
    try {
        String filterSlug = "&s=";
        for (int i = 0; i < numStatuses; i++) {
            if (filterStatus[i])
                filterSlug += String.valueOf(statuses.getInt(statusNames.getString(i))) + "-";
        }
        if (filterSlug.length() > 3) {
            filterSlug = filterSlug.substring(0, filterSlug.length() - 1);
            projDetailURL += filterSlug;
        }
        filterSlug = "&p=";
        for (int i = 0; i < numPriorities; i++) {
            if (filterPriority[i])
                filterSlug += String.valueOf(priorities.getInt(priorityNames.getString(i))) + "-";
        }
        if (filterSlug.length() > 3) {
            filterSlug = filterSlug.substring(0, filterSlug.length() - 1);
            projDetailURL += filterSlug;
        }
    } catch (JSONException e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return new String();
    }
    return projDetailURL;
}

From source file:org.cloudsky.cordovaPlugins.BarcodeminCDV.java

/**
 * Starts an intent to scan and decode a barcode.
 */// w  ww.ja va  2  s. c om
public void scan(final JSONArray args) {

    final CordovaPlugin that = this;

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            Intent intentScan = new Intent(SCAN_INTENT);
            intentScan.addCategory(Intent.CATEGORY_DEFAULT);

            // add config as intent extras
            if (args.length() > 0) {

                JSONObject obj;
                JSONArray names;
                String key;
                Object value;

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

                    try {
                        obj = args.getJSONObject(i);
                    } catch (JSONException e) {
                        Log.i("CordovaLog", e.getLocalizedMessage());
                        continue;
                    }

                    names = obj.names();
                    for (int j = 0; j < names.length(); j++) {
                        try {
                            key = names.getString(j);
                            value = obj.get(key);

                            if (value instanceof Integer) {
                                intentScan.putExtra(key, (Integer) value);
                            } else if (value instanceof String) {
                                intentScan.putExtra(key, (String) value);
                            }

                        } catch (JSONException e) {
                            Log.i("CordovaLog", e.getLocalizedMessage());
                        }
                    }

                    intentScan.putExtra(Intents.Scan.CAMERA_ID,
                            obj.optBoolean(PREFER_FRONTCAMERA, false) ? 1 : 0);
                    intentScan.putExtra(Intents.Scan.SHOW_FLIP_CAMERA_BUTTON,
                            obj.optBoolean(SHOW_FLIP_CAMERA_BUTTON, false));
                    if (obj.has(FORMATS)) {
                        intentScan.putExtra(Intents.Scan.FORMATS, obj.optString(FORMATS));
                    }
                    if (obj.has(PROMPT)) {
                        intentScan.putExtra(Intents.Scan.PROMPT_MESSAGE, obj.optString(PROMPT));
                    }
                    //if (obj.has(ORIENTATION)) {
                    //intentScan.putExtra(Intents.Scan.ORIENTATION_LOCK, obj.optString(ORIENTATION));
                    intentScan.putExtra(Intents.Scan.ORIENTATION_LOCK, "false");
                    //}
                }

            }

            // avoid calling other phonegap apps
            intentScan.setPackage(that.cordova.getActivity().getApplicationContext().getPackageName());

            that.cordova.startActivityForResult(that, intentScan, REQUEST_CODE);
        }
    });
}

From source file:com.vk.sdk.util.VKJsonHelper.java

/**
 * Check if json object is empty/* w  ww .java  2 s  . c o m*/
 *
 * @param object object to check
 * @return true if object is empty
 */
public static boolean isEmptyObject(JSONObject object) {
    return object.names() == null;
}

From source file:org.dasein.cloud.joyent.JoyentDataCenter.java

@Override
public @Nonnull Collection<Region> listRegions() throws InternalException, CloudException {
    JoyentMethod method = new JoyentMethod(provider);
    String json = method.doGetJson(provider.getEndpoint(), "datacenters");

    try {/*  w  ww .  jav a 2  s . com*/
        ArrayList<Region> regions = new ArrayList<Region>();

        JSONObject ob = new JSONObject(json);
        JSONArray ids = ob.names();

        for (int i = 0; i < ids.length(); i++) {
            String regionId = ids.getString(i);
            Region r = new Region();

            r.setActive(true);
            r.setAvailable(true);
            r.setJurisdiction("US");
            r.setName(regionId);
            r.setProviderRegionId(regionId);
            regions.add(r);
        }
        return regions;
    } catch (JSONException e) {
        throw new CloudException(e);
    }
}

From source file:m2.android.archetype.example.FacebookSdk.internal.Utility.java

static Map<String, Object> convertJSONObjectToHashMap(JSONObject jsonObject) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    JSONArray keys = jsonObject.names();
    for (int i = 0; i < keys.length(); ++i) {
        String key;//from w  w w.  j  a v a 2s  .c  om
        try {
            key = keys.getString(i);
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                value = convertJSONObjectToHashMap((JSONObject) value);
            }
            map.put(key, value);
        } catch (JSONException e) {
        }
    }
    return map;
}

From source file:de.joinout.criztovyl.tools.json.JSONMap.java

/**
 * Creates a new {@link JSONMap} from a {@link JSONObject}.
 * @param json the JSON data//from   ww w.  j a  v  a 2s . com
 * @param keyJ the {@link JSONCreator} for the keys
 * @param valJ the {@link JSONCreator} for the values
 */
public JSONMap(JSONObject json, JSONCreator<K> keyJ, JSONCreator<V> valJ) {

    //Set up variables
    this.json = json;
    map = new HashMap<>();

    //Check whether key can be string
    if (keyJ.canBeString()) { //If so, add as string

        //Iterate over map names.
        //If map is empty, names will be null so create an empty array if names are null.
        for (String key : new JSONStringArrayIterator(json.names() == null ? new JSONArray() : json.names()))

            //If value also can be a string, but as one
            map.put(keyJ.fromString(key), valJ.canBeString() ? valJ.fromString(json.getString(key))
                    : valJ.fromJSON(json.getJSONObject(key)));
    } else { //If not, put the JSON-representation

        //Set up arrays of keys and values
        JSONArray keys = json.getJSONArray(KEYS);
        JSONArray values = json.getJSONArray(VALUES);

        //Iterate over key array and take values from the arrays
        for (int i = 0; i < keys.length(); i++)

            //If value can be a string, load as one
            map.put(keyJ.fromJSON(keys.getJSONObject(i)),
                    valJ.canBeString() ? valJ.fromString(values.getString(i))
                            : valJ.fromJSON(values.getJSONObject(i)));
    }
}

From source file:com.hichinaschool.flashcards.libanki.Decks.java

public void load(String decks, String dconf) {
    mDecks = new HashMap<Long, JSONObject>();
    mDconf = new HashMap<Long, JSONObject>();
    try {/*from   w w w.j  av  a2s. c o m*/
        JSONObject decksarray = new JSONObject(decks);
        JSONArray ids = decksarray.names();
        for (int i = 0; i < ids.length(); i++) {
            String id = ids.getString(i);
            JSONObject o = decksarray.getJSONObject(id);
            long longId = Long.parseLong(id);
            mDecks.put(longId, o);
        }
        JSONObject confarray = new JSONObject(dconf);
        ids = confarray.names();
        for (int i = 0; i < ids.length(); i++) {
            String id = ids.getString(i);
            mDconf.put(Long.parseLong(id), confarray.getJSONObject(id));
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    mChanged = false;
}