Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray(Object array) throws JSONException 

Source Link

Document

Construct a JSONArray from an array

Usage

From source file:JSON.GenererJSONSave.java

/**
 * Methode pour sauvegarder le plateau d'un jeu
 * @param p //from www  .j av a  2s . c o  m
 */
public void Save(Plateau p) {
    ArrayList<Sauvegarde> Liste = new ArrayList();
    int k = 0;
    for (int i = 0; i < p.getAbsci(); i++) {
        for (int j = 0; j < p.getOrdonne(); j++) {
            if (p.grille[i][j] != null)
                Liste.add(new Sauvegarde(i, j, p.grille[i][j].nom));

        }
    }
    JSONObject objet = new JSONObject();
    JSONArray jsArray = new JSONArray(Liste);
    objet.put("coordonne", jsArray);
    // Cration du fichier de sortie
    FileWriter fs = null;
    try {
        fs = new FileWriter("C:\\Users\\Alphonse\\Desktop\\output2.txt");
    } catch (IOException e) {
        System.err.println("Erreur lors de l'ouverture du fichier ");
        System.err.println(e);
        System.exit(-1);
    }

    // Sauvegarde dans le fichier
    try {
        objet.write(fs);
        fs.flush();
    } catch (IOException e) {
        System.err.println("Erreur lors de l'criture dans le fichier : " + e);
        System.exit(-1);
    }
}

From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java

/**
 * Called when JS sends the message.//from   ww w.  j  ava2 s .  co  m
 * 
 * @param bridge
 *            Receiver instance.
 * @param code
 *            The code name. This looks like the name of function.
 * @param message
 *            The message. This looks like the argument of function. This is
 *            usually expressed as JSON.
 */
@Override
public void onArriveMessage(JSBridge bridge, String code, String message) {
    if (code == null) {
    } else if (code.equals("onLoad")) {
        this.mMaptypeList = new ArrayList<ValueText<String>>();
        this.mLoaded = true;
        // executes queued commands.
        this.execute(null);
        JSONArray json = null;
        try {
            json = new JSONArray(message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (json != null) {
            for (int n = 0; n < json.length(); n++) {
                JSONObject one = null;
                try {
                    one = json.getJSONObject(n);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (one != null) {
                    String id = null, name = null;
                    try {
                        id = one.getString("id");
                        name = one.getString("name");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (id != null && name != null) {
                        this.mMaptypeList.add(new ValueText<String>(id, name));
                    }
                }
            }
        }
        // restores map state (2013/08/07)
        if (this.mInternalMapState != null) {
            this.restoreMapState(this.mInternalMapState.id, this.mInternalMapState.lon,
                    this.mInternalMapState.lat, this.mInternalMapState.z);
            this.mInternalMapState = null;
        }
        // request to create menu items.
        this.invalidateOptionsMenuIfPossible();
    } else if (code.equals("getCurrentMapState")) {
        if (message == null || !(message.length() > 0)) {
            // DOES NOTHING
        } else {
            try {
                JSONObject json = new JSONObject(message);
                this.mInternalMapState = new MapState();
                this.mInternalMapState.id = json.getString("id");
                this.mInternalMapState.lat = json.getDouble("lat");
                this.mInternalMapState.lon = json.getDouble("lon");
                this.mInternalMapState.z = json.getInt("z");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        this.mWaitingForgetCurrentMapState = false;
    } else if (code.equals("getCurrentZoomState")) {
        if (message == null) {
            // DOES NOTHING
        } else {
            try {
                JSONObject json = new JSONObject(message);
                this.mZoomState = new ZoomState();
                this.mZoomState.minzoom = json.getInt("minzoom");
                this.mZoomState.maxzoom = json.getInt("maxzoom");
                this.mZoomState.currentzoom = json.getInt("currentzoom");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            this.mWaitingForgetCurrentZoomState = false;
        }
    } else if (code.equals("alert")) {
        // shows alert text.
        (new AlertDialog.Builder(this)).setTitle(this.getTitle()).setMessage(message != null ? message : "")
                .setCancelable(true).setPositiveButton(android.R.string.ok, null).show();
    }
}

From source file:com.microsoft.research.webngram.service.impl.LookupServiceImpl.java

@Override
public List<Double> getConditionalProbabilities(String authorizationToken, String modelUrn,
        List<String> phrases) {
    try {//from  www .j  a v a  2s . co m
        List<Double> probabilities = new ArrayList<Double>();
        NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder(
                NgramServiceApiUrls.GET_CONDITIONAL_PROBABILITIES_URL);
        String apiUrl = urlBuilder.withField(ParameterNames.MODEL_URL, modelUrn)
                .withParameter(ParameterNames.USER_TOKEN, authorizationToken).buildUrl();
        JSONArray array = new JSONArray(
                convertStreamToString(callApiMethod(apiUrl, getPostBody(phrases), null, "POST", 200)));
        for (int i = 0; i < array.length(); i++) {
            probabilities.add(array.getDouble(i));
        }
        return probabilities;
    } catch (Exception e) {
        throw new NgramServiceException("An error occurred while getting conditional probabilities.", e);
    }
}

From source file:com.microsoft.research.webngram.service.impl.LookupServiceImpl.java

@Override
public List<String> getModels() {
    try {//  w ww  .  j  a  v  a  2  s.  c om
        List<String> models = new ArrayList<String>();
        NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder(NgramServiceApiUrls.LOOKUP_URL);
        String apiUrl = urlBuilder.buildUrl();
        JSONArray array = new JSONArray(convertStreamToString(callApiGet(apiUrl)));
        for (int i = 0; i < array.length(); i++) {
            models.add(array.getString(i));
        }
        return models;
    } catch (Exception e) {
        throw new NgramServiceException("An error occurred while getting models.", e);
    }
}

From source file:com.microsoft.research.webngram.service.impl.LookupServiceImpl.java

@Override
public List<Double> getProbabilities(String authorizationToken, String modelUrn, List<String> phrases) {
    try {/*  w  ww. j  a  va 2 s  .  c om*/
        List<Double> probabilities = new ArrayList<Double>();
        NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder(
                NgramServiceApiUrls.GET_PROBABILITIES_URL);
        String apiUrl = urlBuilder.withField(ParameterNames.MODEL_URL, modelUrn)
                .withParameter(ParameterNames.USER_TOKEN, authorizationToken).buildUrl();
        JSONArray array = new JSONArray(
                convertStreamToString(callApiMethod(apiUrl, getPostBody(phrases), null, "POST", 200)));
        for (int i = 0; i < array.length(); i++) {
            probabilities.add(array.getDouble(i));
        }
        return probabilities;
    } catch (Exception e) {
        throw new NgramServiceException("An error occurred while getting probabilities.", e);
    }
}

From source file:com.ca.mas.cordova.storage.MASStoragePlugin.java

private void keySetForModeLocal(final JSONArray args, final CallbackContext callbackContext) {
    try {//from  w  w  w  .j  a  v a 2s  .  c om
        MASStorage storage = new MASSecureLocalStorage();
        int segment_0 = args.getInt(0);
        int segment = fetchSegmentLocal(segment_0);

        storage.keySet(segment, new MASCallback<Set<String>>() {
            @Override
            public void onSuccess(Set<String> result) {
                JSONArray array = new JSONArray(result);
                success(callbackContext, array, false);
            }

            @Override
            public void onError(Throwable e) {
                LOG.e(TAG, e.getMessage());
                callbackContext.error(getError(e));
            }
        });
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        callbackContext.error(getError(e));
    }
}

From source file:com.ca.mas.cordova.storage.MASStoragePlugin.java

private void keySetForModeCloud(final JSONArray args, final CallbackContext callbackContext) {
    try {/*from w ww  .j av a  2s . c  om*/
        MASStorage storage = new MASSecureStorage();
        int segment_0 = args.getInt(0);
        int segment = fetchSegmentCloud(segment_0);

        storage.keySet(segment, new MASCallback<Set<String>>() {
            @Override
            public void onSuccess(Set<String> result) {
                JSONArray array = new JSONArray(result);
                success(callbackContext, array, false);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, e.getMessage(), e);
                callbackContext.error(getError(e));
            }
        });
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        callbackContext.error(getError(e));
    }
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java

private List<DownloadItem> retrieveCategories() throws Exception {
    List<DownloadItem> diList = new LinkedList<DownloadItem>();
    JSONArray jsonArray = new JSONArray(downloadJSONString(SS_API_GET_CATEGORIES));
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonItem = jsonArray.getJSONObject(i);
        DownloadItem di = new DownloadItem();
        di.setType(DownloadItem.TYPE_CATEGORY);
        di.setTitle(jsonItem.getString("name"));
        di.setExtras("id", jsonItem.getString("id"));
        di.setExtras("pid", jsonItem.getString("parentId"));
        di.setExtras("page", "1");

        if (di.getTitle() != null) {
            diList.add(di);//w  ww.  j  av a  2 s  .  c om
        }
    }
    return diList;
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java

private List<DownloadItem> retrieveDatabaseList(DownloadItem category) throws Exception {
    List<DownloadItem> diList = new LinkedList<DownloadItem>();
    String url = SS_API_GET_CATEGORY_CONTENT + category.getExtras("id");
    String page = category.getExtras("page");
    if (page != null) {
        url += "&page=" + page;
    } else {/*from   w ww .java2s  . com*/
        page = "1";
    }

    JSONArray jsonArray = new JSONArray(downloadJSONString(url));
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonItem = jsonArray.getJSONObject(i);
        DownloadItem di = new DownloadItem();
        di.setType(DownloadItem.TYPE_DATABASE);
        di.setTitle(jsonItem.getString("stackName"));
        di.setDescription(jsonItem.getString("description"));
        di.setExtras("id", jsonItem.getString("id"));
        di.setAddress(SS_API_GET_DECK + jsonItem.getString("id"));
        di.setExtras("page", page);
        if (di.getTitle() != null) {
            diList.add(di);
        }
    }
    return diList;
}

From source file:com.aokp.romcontrol.github.tasks.GetJSONChangelogTask.java

protected Void doInBackground(Void... unused) {
    HttpClient httpClient = null;/*from   w w w  . ja v  a  2 s .c o m*/
    try {
        httpClient = new DefaultHttpClient();
        String url = String.valueOf(STATIC_DEBUG ? "https://raw.github.com/JBirdVegas/tests/master/example.json"
                : mConfig.CHANGELOG_JSON);
        HttpGet requestWebsite = new HttpGet(url);
        Log.d(TAG, "attempting to connect to: " + url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        JSONArray projectCommitsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler));

        // debugging
        if (DEBUG)
            Log.d(TAG, "projectCommitsArray.length() is: " + projectCommitsArray.length());
        if (Config.StaticVars.JSON_SPEW)
            Log.d(TAG, "projectCommitsArray.toString() is: " + projectCommitsArray.toString());

        final ChangelogObject commitObject = new ChangelogObject(new JSONObject());
        for (int i = 0; i < projectCommitsArray.length(); i++) {
            JSONObject projectsObject = (JSONObject) projectCommitsArray.get(i);
            PreferenceScreen newCommitPreference = mCategory.getPreferenceManager()
                    .createPreferenceScreen(mContext);
            commitObject.reParse(projectsObject);
            newCommitPreference.setTitle(commitObject.getSubject());
            newCommitPreference.setSummary(commitObject.getBody());
            newCommitPreference.setKey(commitObject.getCommitHash());
            newCommitPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    mAlertDialog.setCommitAndShow(commitObject);
                    return false;
                }
            });
            mCategory.addPreference(newCommitPreference);
        }
    } catch (HttpResponseException httpError) {
        Log.e(TAG, "bad HTTP response:", httpError);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "client protocal exception:", e);
    } catch (JSONException e) {
        Log.d(TAG, "bad json interaction:", e);
    } catch (IOException e) {
        Log.d(TAG, "io exception:", e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return null;
}