Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:GUI.simplePanel.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {//  w  ww  .  java 2  s.com
        String reply = util.httpRequest.sendPost("127.0.0.1", 8383, "", "/getServices");
        JSONObject obj;

        obj = new JSONObject(reply);
        JSONArray services = obj.getJSONArray("services");
        boolean found = false;
        for (int i = 0; i < services.length(); i++) {
            if (found) {
                return;
            }
            Object pref = services.getJSONObject(i).get("url");
            String url = (String) pref;
            if (url.contains("temp")) {
                // http://127.0.0.1:8181/sensor/1/temp
                String serviceHost = (url.split(":")[1].substring(2));
                int Port = Integer.parseInt((url.split(":")[2]).split("/")[0]);
                String servicePath = (url.split(":")[2].substring(url.split(":")[2].indexOf("/")));
                String serviceReply = util.httpRequest.sendPost(serviceHost, Port, "", servicePath);

                JSONObject temperature;

                obj = new JSONObject(serviceReply);
                String temp = obj.getJSONObject("sensor").getString("Temperature");
                JOptionPane.showMessageDialog(self,
                        "Temperature is " + temp.substring(0, temp.indexOf(".") + 2) + " Celsius");
                found = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.facebook.login.LoginLogger.java

public void logCompleteLogin(String loginRequestId, Map<String, String> loggingExtras,
        LoginClient.Result.Code result, Map<String, String> resultExtras, Exception exception) {

    Bundle bundle = newAuthorizationLoggingBundle(loginRequestId);
    if (result != null) {
        bundle.putString(EVENT_PARAM_LOGIN_RESULT, result.getLoggingValue());
    }//from  w  ww  . ja  v  a  2  s. c  o  m
    if (exception != null && exception.getMessage() != null) {
        bundle.putString(EVENT_PARAM_ERROR_MESSAGE, exception.getMessage());
    }

    // Combine extras from the request and from the result.
    JSONObject jsonObject = null;
    if (loggingExtras.isEmpty() == false) {
        jsonObject = new JSONObject(loggingExtras);
    }
    if (resultExtras != null) {
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        try {
            for (Map.Entry<String, String> entry : resultExtras.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
        } catch (JSONException e) {
        }
    }
    if (jsonObject != null) {
        bundle.putString(EVENT_PARAM_EXTRAS, jsonObject.toString());
    }

    appEventsLogger.logSdkEvent(EVENT_NAME_LOGIN_COMPLETE, null, bundle);
}

From source file:com.facebook.login.LoginLogger.java

public void logAuthorizationMethodComplete(String authId, String method, String result, String errorMessage,
        String errorCode, Map<String, String> loggingExtras) {

    Bundle bundle;//from ww  w .  j a v a2s  .c  om
    bundle = LoginLogger.newAuthorizationLoggingBundle(authId);
    if (result != null) {
        bundle.putString(LoginLogger.EVENT_PARAM_LOGIN_RESULT, result);
    }
    if (errorMessage != null) {
        bundle.putString(LoginLogger.EVENT_PARAM_ERROR_MESSAGE, errorMessage);
    }
    if (errorCode != null) {
        bundle.putString(LoginLogger.EVENT_PARAM_ERROR_CODE, errorCode);
    }
    if (loggingExtras != null && !loggingExtras.isEmpty()) {
        JSONObject jsonObject = new JSONObject(loggingExtras);
        bundle.putString(LoginLogger.EVENT_PARAM_EXTRAS, jsonObject.toString());
    }
    bundle.putString(EVENT_PARAM_METHOD, method);

    appEventsLogger.logSdkEvent(EVENT_NAME_LOGIN_METHOD_COMPLETE, null, bundle);
}

From source file:org.loklak.api.geo.GeocodeServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;/*  w  w w  .jav a 2 s .c  om*/
    }

    // parameters
    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    boolean minified = post.get("minified", false);
    String data = post.get("data", "");
    String places = post.get("places", "");
    if (places.length() == 0 && data.length() == 0) {
        response.sendError(503,
                "you must submit a data attribut with a json containing the property 'places' with a list of place names");
        return;
    }

    String[] place = new String[0];
    if (places.length() > 0) {
        place = places.split(",");
    } else {
        // parse the json data
        try {
            JSONObject json = new JSONObject(data);
            if (json.has("places") && json.get("places") instanceof JSONArray) {
                JSONArray p = json.getJSONArray("places");
                place = new String[p.length()];
                int i = 0;
                for (Object o : p)
                    place[i++] = (String) o;
            } else {
                response.sendError(400, "submitted data is not well-formed: expected a list of strings");
                return;
            }
        } catch (IOException e) {
            Log.getLog().warn(e);
        }
    }

    // find locations for places
    JSONObject locations = new JSONObject(true);
    for (String p : place) {
        GeoMark loc = DAO.geoNames.analyse(p, null, 5, Long.toString(System.currentTimeMillis()));
        if (loc != null) {
            locations.put(p, loc.toJSON(minified));
        } else {
            locations.put(p, new JSONObject());
        }
    }

    post.setResponse(response, "application/javascript");

    // generate json
    JSONObject m = new JSONObject(true);
    m.put("locations", locations);

    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(m.toString(minified ? 0 : 2));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:com.spoiledmilk.cykelsuperstier.break_rote.BreakRouteActivity.java

private void parseStationsFromJson() {
    metroStations = new ArrayList<OverlayData>();
    sTrainStations = new ArrayList<OverlayData>();
    localTrainStations = new ArrayList<OverlayData>();
    try {//from   w  w  w. j av  a  2  s . c  om
        String stationsStr = Util.stringFromJsonAssets(this, "stations/stations.json");
        JSONArray stationsJson = (new JSONObject(stationsStr)).getJSONArray("stations");
        for (int i = 0; i < stationsJson.length(); i++) {
            JSONObject stationJson = (JSONObject) stationsJson.get(i);
            if (!stationJson.has("coords"))
                continue;
            String[] coords = stationJson.getString("coords").split("\\s+");
            String type = stationJson.getString("type");
            if (type.equals("service")) {
                continue;
            } else if (type.equals("metro")) {
                metroStations.add(new OverlayData(stationJson.getString("name"), stationJson.getString("line"),
                        Double.parseDouble(coords[1]), Double.parseDouble(coords[0]),
                        R.drawable.metro_logo_pin));
            } else if (type.equals("s-train")) {
                sTrainStations.add(new OverlayData(stationJson.getString("name"), stationJson.getString("line"),
                        Double.parseDouble(coords[1]), Double.parseDouble(coords[0]),
                        R.drawable.list_subway_icon));
            } else if (type.equals("local-train")) {
                localTrainStations.add(new OverlayData(stationJson.getString("name"),
                        stationJson.getString("line"), Double.parseDouble(coords[1]),
                        Double.parseDouble(coords[0]), R.drawable.list_subway_icon));
            }
        }
    } catch (Exception e) {
        LOG.e(e.getLocalizedMessage());
    }
}

From source file:org.wso2.appmanager.integration.test.cases.PublisherCreateWebAppTestCase.java

@Test(description = TEST_DESCRIPTION)
public void testPublisherCreateWebApp() throws Exception {
    HttpResponse appCreateResponse = appmPublisherRestClient.webAppCreate(appName, context, appVersion,
            trackingCode, appCreatorUserName);
    int appCreateResponseCode = appCreateResponse.getResponseCode();
    assertTrue(appCreateResponseCode == 200, appCreateResponseCode + " status code received.");
    JSONObject appCreateResponseData = new JSONObject(appCreateResponse.getData());
    assertEquals(appCreateResponseData.getString(AppmTestConstants.MESSAGE), "asset added",
            "Asset has not added successfully");
    assertNotNull(appCreateResponseData.getString(AppmTestConstants.ID), "app id is null");
}

From source file:org.onepf.oms.data.SkuDetails.java

public SkuDetails(String json) throws JSONException {
    JSONObject o = new JSONObject(json);
    _sku = o.getString("productId");
    _type = o.optString("type");
    _price = o.optString("price");
    _title = o.optString("title");
    _description = o.optString("description");
}

From source file:de.schildbach.wallet.data.ExchangeRatesProvider.java

private Map<String, ExchangeRate> requestExchangeRates() {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(BITCOINAVERAGE_URL);
    request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {//from w  w w  .  j  a v a2  s . c o  m
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final String content = response.body().string();
            final JSONObject head = new JSONObject(content);
            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (currencyCode.startsWith("BTC")) {
                    final String fiatCurrencyCode = currencyCode.substring(3);
                    if (!fiatCurrencyCode.equals(MonetaryFormat.CODE_BTC)
                            && !fiatCurrencyCode.equals(MonetaryFormat.CODE_MBTC)
                            && !fiatCurrencyCode.equals(MonetaryFormat.CODE_UBTC)) {
                        final JSONObject exchangeRate = head.getJSONObject(currencyCode);
                        final JSONObject averages = exchangeRate.getJSONObject("averages");
                        try {
                            final Fiat rate = parseFiatInexact(fiatCurrencyCode, averages.getString("day"));
                            if (rate.signum() > 0)
                                rates.put(fiatCurrencyCode, new ExchangeRate(
                                        new org.bitcoinj.utils.ExchangeRate(rate), BITCOINAVERAGE_SOURCE));
                        } catch (final IllegalArgumentException x) {
                            log.warn("problem fetching {} exchange rate from {}: {}", currencyCode,
                                    BITCOINAVERAGE_URL, x.getMessage());
                        }
                    }
                }
            }

            watch.stop();
            log.info("fetched exchange rates from {}, {} chars, took {}", BITCOINAVERAGE_URL, content.length(),
                    watch);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", response.code(),
                    BITCOINAVERAGE_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + BITCOINAVERAGE_URL, x);
    }

    return null;
}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private U2FContext parseU2FContext(String data) {
    try {/*  ww  w  .j  a va  2s . c o  m*/
        JSONObject json = new JSONObject(data);
        String requestType = json.getString(TAG_JSON_TYPE);
        if (requestType.equals(SIGN_REQUEST_TYPE)) {
            return parseU2FContextSign(json);
        } else if (requestType.equals(REGISTER_REQUEST_TYPE)) {
            return parseU2FContextRegister(json);
        } else {
            Log.e(TAG, "Invalid request type");
            return null;
        }
    } catch (JSONException e) {
        Log.e(TAG, "Error decoding request");
        return null;
    }

}

From source file:com.jellymold.boss.ImageSearch.java

/**
 * Performs a search based on the search string parameter
 * and the filter parameter//from  ww w  .ja  v  a2  s. co  m
 *
 * Sets the value of search string and filter for this instance.
 *
 * @param search - the search string
 * @param filter - filter results or not
 * @return - HTTP response code
 * @throws BOSSException runtime exception
 */
public int search(String search, boolean filter) throws BOSSException {

    setFiltered(filter);

    setSearchString(search);

    String params = "appid=" + getAppKey();

    if (isFiltered()) {
        params += "&filtered=yes";
    }

    try {

        setResponseCode(getHttpRequest()
                .sendGetRequest(getServer() + getEndPoint() + URLEncoder.encode(search) + "?" + params));
        if (HTTP_OK == getResponseCode()) {
            JSONObject searchResults = new JSONObject(getHttpRequest().getResponseBody())
                    .getJSONObject("ysearchresponse");
            this.parseResults(searchResults);
        }
    } catch (JSONException e) {
        setResponseCode(500);
        throw new BOSSException("JSON Exception parsing image search results", e);
    } catch (IOException ioe) {
        setResponseCode(500);
        throw new BOSSException("IO Exception", ioe);
    }

    return getResponseCode();

}