Example usage for org.json JSONArray toString

List of usage examples for org.json JSONArray toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONArray.

Usage

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public ArrayList<String> getImageURLs(Status status, Twitter twitter) {

    ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status);
    try {/*from   w w  w  .j  ava  2  s  . c o m*/
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/show/" + status.getId() + ".json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/show/" + status.getId() + ".json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);
        String responseBody = EntityUtils.toString(response2.getEntity());
        conn.close();

        JSONObject fullJson = new JSONObject(responseBody);
        JSONObject extendedEntities = fullJson.getJSONObject("extended_entities");
        JSONArray media = extendedEntities.getJSONArray("media");

        Log.v("talon_images", media.toString());

        for (int i = 0; i < media.length(); i++) {
            JSONObject entity = media.getJSONObject(i);
            try {
                // parse through the objects and get the media_url
                String url = entity.getString("media_url");
                String type = entity.getString("type");

                // want to check to make sure it doesn't have it already
                // this also checks to confirm that the entity is in fact a photo
                if (!images.contains(url) && type.equals("photo")) {
                    images.add(url);
                }
            } catch (Exception e) {

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return images;
}

From source file:com.imos.sample.pi.LedBlink.java

public void pythonTemperatureSensor() {

    try {/*  w  w w  . ja  va  2  s  .  c  om*/
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (!result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, "");
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                try (BufferedWriter writer = new BufferedWriter(
                        new FileWriter(builder.toString() + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("src/main/resources/" + dirName);
                    newDir.mkdir();

                    File files = new File("src/main/resources/");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("src/main/resources/" + dirName + file.getName()));
                            file.delete();
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(LedBlink.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.androidsoft.games.memory.kids.model.TileList.java

/**
 * Serialize the List//w  ww.jav  a  2 s  .  c om
 * @return The list as a String
 */
String serialize() {
    JSONArray array = new JSONArray();
    for (Tile t : this) {
        array.put(t.json());
    }
    return array.toString();
}

From source file:org.catnut.metadata.Status.java

@Override
public ContentValues convert(JSONObject json) {
    ContentValues tweet = new ContentValues();
    tweet.put(BaseColumns._ID, json.optLong(Constants.ID));
    tweet.put(created_at, json.optString(created_at));
    // ?jsonsql???
    tweet.put(columnText, json.optString(text));
    tweet.put(source, json.optString(source));
    tweet.put(favorited, json.optBoolean(favorited));
    tweet.put(truncated, json.optBoolean(truncated));
    // ??????/*from   w  w  w . ja va 2 s .  com*/
    JSONArray thumbs = json.optJSONArray(pic_urls);
    if (thumbs != null) {
        // json
        tweet.put(pic_urls, thumbs.toString());
    }
    tweet.put(thumbnail_pic, json.optString(thumbnail_pic));
    tweet.put(bmiddle_pic, json.optString(bmiddle_pic));
    tweet.put(original_pic, json.optString(original_pic));
    // ???
    if (json.has(retweeted_status)) {
        tweet.put(retweeted_status, json.optJSONObject(retweeted_status).toString());
    }
    // 
    if (json.has(User.SINGLE)) {
        tweet.put(uid, json.optJSONObject(User.SINGLE).optLong(Constants.ID));
    } else if (json.has(uid)) {
        tweet.put(uid, json.optLong(uid));
    }
    tweet.put(reposts_count, json.optInt(reposts_count));
    tweet.put(comments_count, json.optInt(comments_count));
    tweet.put(attitudes_count, json.optInt(attitudes_count));
    return tweet;
}

From source file:com.bangz.shotrecorder.SplitManager.java

String toJSONString() {
    JSONArray jsonArray = new JSONArray();

    int SHOTS = getNumbers();

    for (int i = 0; i < SHOTS; i++) {
        jsonArray.put(getSplits().get(i).getTime());
    }/*w w  w.ja  v  a2 s  . com*/

    return jsonArray.toString();

}

From source file:com.kercer.kernet.http.request.KCJsonArrayRequest.java

/**
 * Creates a new request.//  w  w w  .j  a  v  a  2 s . c  o  m
 *
 * @param method
 *            the HTTP method to use
 * @param url
 *            URL to fetch the JSON from
 * @param jsonRequest
 *            A {@link JSONArray} to post with the request. Null is allowed and indicates no parameters will be posted along with request.
 * @param listener
 *            Listener to receive the JSON response
 * @param errorListener
 *            Error listener, or null to ignore errors.
 */
public KCJsonArrayRequest(int method, String url, JSONArray jsonRequest,
        KCHttpResultListener<JSONArray> listener, KCHttpListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);

    parserResponse();
}

From source file:cz.vse.fis.keg.entityclassifier.exporter.JSONExporter.java

public String toJSON(List<Entity> entities) {
    String jsonResult = "";
    try {/*from  w  ww .  j  a v a2  s .  co m*/

        JSONArray jsonEntities = new JSONArray();

        for (Entity e : entities) {

            JSONObject jsonE = new JSONObject();
            jsonE.put("entityType", e.getEntityType());
            jsonE.put("underlyingString", e.getUnderlyingString());
            jsonE.put("startOffset", e.getStartOffset());
            jsonE.put("endOffset", e.getEndOffset());
            ArrayList<Type> types = e.getTypes();

            JSONArray typesJ = new JSONArray();

            if (types != null) {
                for (Type t : types) {

                    JSONObject typeJ = new JSONObject();

                    String tLabel = t.getTypeLabel();
                    if (tLabel != null) {
                        typeJ.put("typeLabel", t.getTypeLabel());
                    } else {
                        String tmp = null;
                        typeJ.put("typeLabel", JSONObject.NULL);
                    }

                    String tURI = t.getTypeURI();
                    if (tURI != null) {
                        typeJ.put("typeURI", t.getTypeURI());
                    } else {
                        String tmp = null;
                        typeJ.put("typeURI", JSONObject.NULL);
                    }

                    typeJ.put("entityLabel", t.getEntityLabel());
                    typeJ.put("entityURI", t.getEntityURI());

                    Confidence classificationConf = t.getClassificationConfidence();

                    if (classificationConf != null) {

                        JSONObject confValueJ = new JSONObject();
                        confValueJ.put("value", classificationConf.getValue());

                        if (classificationConf.getType() != null) {
                            confValueJ.put("type", classificationConf.getType());
                        } else {
                            confValueJ.put("type", "classification");
                        }
                        typeJ.put("classificationConfidence", confValueJ);
                    } else {
                        JSONObject confValueJ = new JSONObject();
                        confValueJ.put("value", -1);
                        confValueJ.put("type", "classification");
                        typeJ.put("classificationConfidence", confValueJ);
                    }

                    // create element linking confidence
                    Confidence linkingConf = t.getLinkingConfidence();
                    if (linkingConf != null) {
                        JSONObject linkValueJ = new JSONObject();
                        linkValueJ.put("value", linkingConf.getValue());
                        if (linkingConf.getType() != null) {
                            linkValueJ.put("type", linkingConf.getType());
                        }
                        typeJ.put("linkingConfidence", linkValueJ);
                    } else {
                        JSONObject linkValueJ = new JSONObject();
                        linkValueJ.put("value", -1);
                        linkValueJ.put("type", "linking");
                        typeJ.put("linkingConfidence", linkValueJ);
                    }

                    Salience s = t.getSalience();
                    if (s != null) {
                        JSONObject salienceJ = new JSONObject();
                        salienceJ.put("score", s.getScore());
                        salienceJ.put("confidence", s.getConfidence());
                        salienceJ.put("classLabel", s.getClassLabel());
                        typeJ.put("salience", salienceJ);
                    }

                    typeJ.put("provenance", t.getProvenance());
                    typesJ.put(typeJ);
                }
                jsonE.put("types", typesJ);
            }
            jsonEntities.put(jsonE);
        }

        jsonResult = jsonEntities.toString();
        return jsonResult;

    } catch (Exception ex) {
        Logger.getLogger(JSONExporter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }
    return "problem";
}

From source file:org.marietjedroid.connect.MarietjeMessenger.java

/**
 * Sends a request and handles the response
 * //  w  ww  .j av  a 2 s  .  c  o m
 * @param list
 * @throws MarietjeException
 */
private void doRequest(List<JSONObject> list) throws MarietjeException {
    if (list != null)
        list = new ArrayList<JSONObject>(list);
    else
        list = new ArrayList<JSONObject>();

    HttpClient httpClient = new DefaultHttpClient();
    if (this.token == null) {
        throw new IllegalStateException("token is null");
    }

    JSONArray json = new JSONArray();
    json.put(token);
    for (JSONObject m : list)
        json.put(m);
    HttpGet hp = null;
    try {
        System.out.println("JSON: " + json.toString());
        String url = String.format("http://%s:%s%s?m=%s", host, port, path,
                URLEncoder.encode(json.toString(), "UTF-8"));
        System.out.println("url: " + url);
        hp = new HttpGet(url);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    StringBuilder sb = new StringBuilder();
    try {
        HttpResponse r = httpClient.execute(hp);
        InputStreamReader is = new InputStreamReader(r.getEntity().getContent());
        BufferedReader br = new BufferedReader(is);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println("response: " + line);
            sb.append(line);
        }
    } catch (IOException e) {
        MarietjeException tr = new MarietjeException("Connection stuk!" + e.getMessage());
        this.exception = tr;
        throw tr;
    }

    JSONArray d = null;
    try {
        d = new JSONArray(new JSONTokener(sb.toString()));
    } catch (JSONException e) {
        throw (exception = new MarietjeException("Ja, JSON kapot!"));
    }

    if (d == null || d.length() != 3)
        throw (exception = new MarietjeException("Unexpected length of response list"));
    String token = null;
    JSONArray msgs = null;
    try {
        token = d.getString(0);
        msgs = d.getJSONArray(1);
        // JSONArray stream = d.getJSONArray(2);
    } catch (JSONException e) {
        throw (exception = new MarietjeException("unexpected format of response list"));
    }

    synchronized (this.outSemaphore) {
        String oldToken = this.token;
        this.token = token;

        if (oldToken == null) {
            this.outSemaphore.release();
        }
    }

    for (int i = 0; i < msgs.length(); i++) {
        try {
            System.out.println("adding msg to queue");
            synchronized (queueMessageIn) {
                this.queueMessageIn.add(msgs.getJSONObject(i));
            }
            this.messageInSemaphore.release();
        } catch (JSONException e) {
            System.err.println("ontvangen json kapot");
            e.printStackTrace();
        }
    }

    // TODO Streams left out.

}

From source file:org.creativecommons.thelist.fragments.GalleryFragment.java

public void refreshItems() {
    if (!mCurrentUser.isTempUser()) {
        mRequestMethods.getUserPhotos(new RequestMethods.ResponseCallback() {
            @Override/* www .ja v a2s  .  co m*/
            public void onSuccess(JSONArray response) {
                Log.v(TAG, " > getUserPhotos > onSuccess" + response.toString());
                mPhotoList.clear();

                for (int i = 0; i < response.length(); i++) {
                    GalleryItem galleryItem = new GalleryItem();

                    try {
                        JSONObject singlePhotoItem = response.getJSONObject(i);
                        String photoUrl = singlePhotoItem.getString(ApiConstants.USER_PHOTO_URL);
                        Log.v(TAG, photoUrl);
                        galleryItem.setUrl(photoUrl);

                        if (photoUrl == null) {
                            galleryItem.setProgress(true);
                        }
                        mPhotoList.add(galleryItem);
                    } catch (JSONException e) {
                        Log.v(TAG, e.getMessage());
                    }
                }

                Log.v(TAG, "PHOTOLIST RESPONSE " + mPhotoList);

                mProgressBar.setVisibility(View.INVISIBLE);

                if (mPhotoList.size() == 0) {
                    //TODO: show textView
                    mEmptyView.setText(R.string.empty_gallery_label_logged_in);
                    mEmptyView.setVisibility(View.VISIBLE);
                    Log.v(TAG, "VIEW IS EMPTY");
                } else {
                    //TODO: hide textView
                    mEmptyView.setVisibility(View.GONE);
                    Log.v(TAG, "VIEW HAS PHOTO ITEMS");
                    Collections.reverse(mPhotoList);
                    mGalleryAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(VolleyError error) {
                Log.d(TAG, "> getUserPhotos > onFail: " + error.toString());
            }
        });
    } else {
        mEmptyView.setText(mContext.getString(R.string.empty_gallery_label_temp));
        mEmptyView.setVisibility(View.VISIBLE);
    }
}

From source file:com.adf.bean.AbsBean.java

public String columnValueToString(Object obj) {
    if (obj.getClass().isArray()) {
        JSONArray arr = arrayObjectToJson(obj);
        return arr.toString();
    }//from w  w w .  j a v  a2  s  .  com
    return obj.toString();
}