Example usage for org.json JSONObject getDouble

List of usage examples for org.json JSONObject getDouble

Introduction

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

Prototype

public double getDouble(String key) throws JSONException 

Source Link

Document

Get the double value associated with a key.

Usage

From source file:jessmchung.groupon.parsers.RedemptionLocationParser.java

@Override
public RedemptionLocation parse(JSONObject json) throws JSONException {
    RedemptionLocation obj = new RedemptionLocation();
    if (json.has("streetAddress1"))
        obj.setStreetAddress1(json.getString("streetAddress1"));
    if (json.has("streetAddress2"))
        obj.setStreetAddress2(json.getString("streetAddress2"));
    if (json.has("state"))
        obj.setState(json.getString("state"));
    if (json.has("city"))
        obj.setCity(json.getString("city"));
    if (json.has("lat"))
        obj.setLat(json.getDouble("lat"));
    if (json.has("lng"))
        obj.setLng(json.getDouble("lng"));
    if (json.has("postalCode"))
        obj.setPostalCode(json.getString("postalCode"));
    if (json.has("name"))
        obj.setName(json.getString("name"));

    return obj;/*  w  ww . ja  v a  2 s . c om*/
}

From source file:org.stockchart.series.LinearSeries.java

public void fromJSONObject(JSONObject j) throws JSONException {
    super.fromJSONObject(j);
    fPointSizeInPercents = (float) j.getDouble("pointSize");
    fPointStyle = PointStyle.valueOf(j.getString("pointStyle"));
    fPointsVisible = j.getBoolean("pointsVisible");
    fPointAppearance.fromJSONObject(j.getJSONObject("pointAppearance"));
}

From source file:android.locationprivacy.algorithm.Webservice.java

@Override
public Location obfuscate(Location location) {
    // We do it this way to run network connection in main thread. This
    // way is not the normal one and does not comply to best practices,
    // but the main thread must wait for the obfuscation service reply anyway.
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);//from  w w  w  .j  a v  a 2  s.  c  om

    final String HOST_ADDRESS = configuration.getString("host");
    String username = configuration.getString("username");
    String password = configuration.getString("secret_password");

    Location newLoc = new Location(location);
    double lat = location.getLatitude();
    double lon = location.getLongitude();

    String urlString = HOST_ADDRESS;
    urlString += "?lat=" + lat;
    urlString += "&lon=" + lon;
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Error: could not build URL");
        Log.e(TAG, e.getMessage());
        return null;
    }
    HttpsURLConnection connection = null;
    JSONObject json = null;
    InputStream is = null;
    try {
        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        connection.setRequestProperty("Authorization",
                "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
        is = connection.getInputStream();

    } catch (IOException e) {
        Log.e(TAG, "Error while connectiong to " + url.toString());
        Log.e(TAG, e.getMessage());
        return null;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line = reader.readLine();
        System.out.println("Line " + line);
        json = new JSONObject(line);
        newLoc.setLatitude(json.getDouble("lat"));
        newLoc.setLongitude(json.getDouble("lon"));
    } catch (IOException e) {
        Log.e(TAG, "Error: could not read from BufferedReader");
        Log.e(TAG, e.getMessage());
        return null;
    } catch (JSONException e) {
        Log.e(TAG, "Error: could not read from JSON");
        Log.e(TAG, e.getMessage());
        return null;
    }
    connection.disconnect();
    return newLoc;
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException {
    /*//from   www.  j a  v a  2s. co m
            {
        "architectures":["I32"],
        "id":"m1.small",
        "name":"Small Instance (m1.small)",
        "description":"Small Instance (m1.small)",
        "cpuCount":1,
        "rootVolumeSizeInGb":160,
        "ramSizeInMb": 1700
    },
     */
    VirtualMachineProduct prd = new VirtualMachineProduct();

    try {
        if (json.has("id")) {
            prd.setProviderProductId(json.getString("id"));
        } else {
            return null;
        }
        if (json.has("name")) {
            prd.setName(json.getString("name"));
        } else {
            prd.setName(prd.getProviderProductId());
        }
        if (json.has("description")) {
            prd.setDescription(json.getString("description"));
        } else {
            prd.setDescription(prd.getName());
        }
        if (json.has("cpuCount")) {
            prd.setCpuCount(json.getInt("cpuCount"));
        } else {
            prd.setCpuCount(1);
        }
        if (json.has("rootVolumeSizeInGb")) {
            prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE));
        } else {
            prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
        }
        if (json.has("ramSizeInMb")) {
            prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE));
        } else {
            prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE));
        }
        if (json.has("generation") && json.getString("generation").equalsIgnoreCase("previous")) {
            prd.setStatusDeprecated();
        }
        if (json.has("standardHourlyRates")) {
            JSONArray rates = json.getJSONArray("standardHourlyRates");

            for (int i = 0; i < rates.length(); i++) {
                JSONObject rate = rates.getJSONObject(i);

                if (rate.has("rate")) {
                    prd.setStandardHourlyRate((float) rate.getDouble("rate"));
                }
            }
        }
    } catch (JSONException e) {
        throw new InternalException(e);
    }
    return prd;
}

From source file:com.facebook.config.DoubleExtractor.java

@Override
public Double extract(String key, JSONObject jsonObject) throws JSONException {
    return jsonObject.getDouble(key);
}

From source file:com.hackathon.gavin.string.parser.MyAccountParser.java

public static ArrayList convertToArrayList(JSONArray orginalData) {
    ArrayList<String> allElements = new ArrayList<String>();
    for (int i = 0; i < orginalData.length(); i++) {
        try {//from  w ww.  ja  v a2  s .  co m
            JSONObject obj = orginalData.getJSONObject(i);
            allElements.add(Integer.toString(obj.getInt("id")));
            allElements.add(Integer.toString(obj.getInt("units")));
            allElements.add(obj.getString("instrument"));
            allElements.add(String.valueOf(obj.getDouble("price")));
            System.out.println(allElements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return allElements;
}

From source file:org.openhab.habdroid.model.OpenHABWidget.java

public OpenHABWidget(OpenHABWidget parent, JSONObject widgetJson) {
    this.parent = parent;
    this.children = new ArrayList<OpenHABWidget>();
    this.mappings = new ArrayList<OpenHABWidgetMapping>();
    try {/*from   w w w  .  ja v a 2s  . co  m*/
        if (widgetJson.has("item")) {
            this.setItem(new OpenHABItem(widgetJson.getJSONObject("item")));
        }
        if (widgetJson.has("linkedPage")) {
            this.setLinkedPage(new OpenHABLinkedPage(widgetJson.getJSONObject("linkedPage")));
        }
        if (widgetJson.has("mappings")) {
            JSONArray mappingsJsonArray = widgetJson.getJSONArray("mappings");
            for (int i = 0; i < mappingsJsonArray.length(); i++) {
                JSONObject mappingObject = mappingsJsonArray.getJSONObject(i);
                OpenHABWidgetMapping mapping = new OpenHABWidgetMapping(mappingObject.getString("command"),
                        mappingObject.getString("label"));
                mappings.add(mapping);
            }
        }
        if (widgetJson.has("type"))
            this.setType(widgetJson.getString("type"));
        if (widgetJson.has("widgetId"))
            this.setId(widgetJson.getString("widgetId"));
        if (widgetJson.has("label"))
            this.setLabel(widgetJson.getString("label"));
        if (widgetJson.has("icon"))
            this.setIcon(widgetJson.getString("icon"));
        if (widgetJson.has("url"))
            this.setUrl(widgetJson.getString("url"));
        if (widgetJson.has("minValue"))
            this.setMinValue((float) widgetJson.getDouble("minValue"));
        if (widgetJson.has("maxValue"))
            this.setMaxValue((float) widgetJson.getDouble("maxValue"));
        if (widgetJson.has("step"))
            this.setStep((float) widgetJson.getDouble("step"));
        if (widgetJson.has("refresh"))
            this.setRefresh(widgetJson.getInt("refresh"));
        if (widgetJson.has("period"))
            this.setPeriod(widgetJson.getString("period"));
        if (widgetJson.has("service"))
            this.setService(widgetJson.getString("service"));
        if (widgetJson.has("height"))
            this.setHeight(widgetJson.getInt("height"));
        if (widgetJson.has("iconcolor"))
            this.setIconColor(widgetJson.getString("iconcolor"));
        if (widgetJson.has("labelcolor"))
            this.setLabelColor(widgetJson.getString("labelcolor"));
        if (widgetJson.has("valuecolor"))
            this.setValueColor(widgetJson.getString("valuecolor"));
        if (widgetJson.has("encoding"))
            this.setEncoding(widgetJson.getString("encoding"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (widgetJson.has("widgets")) {
        try {
            JSONArray childWidgetJsonArray = widgetJson.getJSONArray("widgets");
            for (int i = 0; i < childWidgetJsonArray.length(); i++) {
                new OpenHABWidget(this, childWidgetJsonArray.getJSONObject(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    this.parent.addChildWidget(this);
}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *//*w w w  . j  av a2s.c o m*/
public String getRemoteExpenses() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored."));
                Expense.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE,
                                "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString());
                        if (expense == null) {
                            expense = new Expense(expenseJson);
                        } else {
                            expense.setRemoteId(expenseJson.getString("_id"));
                            expense.setAmount(expenseJson.getDouble("amount"));
                            expense.setCategory(expenseJson.getString("category"));
                            expense.setDate(expenseJson.getString("date"));

                            if (expenseJson.has("deviceId")) {
                                expense.setDeviceId(expenseJson.getString("deviceId"));
                            } else {
                                expense.setDeviceId(Device.registeredDevice().getLogin());
                            }
                        }
                        expense.save();

                        if (expenseJson.has("receipts")) {
                            JSONArray receiptsArray = expenseJson.getJSONArray("receipts");

                            for (int j = 0; j < receiptsArray.length(); j++) {
                                JSONObject recJsonObject = receiptsArray.getJSONObject(i);
                                Receipt receipt = new Receipt();
                                receipt.setBase64(recJsonObject.getString("base64"));
                                receipt.setExpense(expense);
                                receipt.setName("");
                                receipt.save();
                            }
                        }
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:PlayerInfo.Player.java

public double getBalance() {
    double currentBalance = 0;
    JSONObject money = new JSONObject();
    try {//from   ww w  .  ja  va2s  . co m
        currentBalance = money.getDouble("balance");

    } catch (JSONException ex) {
        Logger.getLogger(BlackJackPlayRound.class.getName()).log(Level.SEVERE, null, ex);
    }
    return currentBalance;
}

From source file:com.github.cambierr.lorawanpacket.semtech.Rxpk.java

public Rxpk(JSONObject _json) throws MalformedPacketException {

    /**//from w ww  .  j  a  va2  s .  co  m
     * tmst
     */
    if (!_json.has("tmst")) {
        throw new MalformedPacketException("missing tmst");
    } else {
        tmst = _json.getInt("tmst");
    }

    /**
     * time
     */
    if (!_json.has("time")) {
        throw new MalformedPacketException("missing time");
    } else {
        time = _json.getString("time");
    }

    /**
     * chan
     */
    if (!_json.has("chan")) {
        throw new MalformedPacketException("missing chan");
    } else {
        chan = _json.getInt("chan");
    }

    /**
     * rfch
     */
    if (!_json.has("rfch")) {
        throw new MalformedPacketException("missing rfch");
    } else {
        rfch = _json.getInt("rfch");
    }

    /**
     * freq
     */
    if (!_json.has("freq")) {
        throw new MalformedPacketException("missing freq");
    } else {
        freq = _json.getDouble("stat");
    }

    /**
     * stat
     */
    if (!_json.has("stat")) {
        throw new MalformedPacketException("missing stat");
    } else {
        stat = _json.getInt("stat");
        if (stat > 1 || stat < -1) {
            throw new MalformedPacketException("stat must be equal to -1, 0, or 1");
        }
    }

    /**
     * modu
     */
    if (!_json.has("modu")) {
        throw new MalformedPacketException("missing modu");
    } else {
        modu = Modulation.parse(_json.getString("modu"));
    }

    /**
     * datr
     */
    if (!_json.has("datr")) {
        throw new MalformedPacketException("missing datr");
    } else {
        switch (modu) {
        case FSK:
            datr = _json.getInt("datr");
            break;
        case LORA:
            datr = _json.getString("datr");
            break;
        }
    }

    /**
     * codr
     */
    if (!_json.has("codr")) {
        if (modu.equals(Modulation.FSK)) {
            codr = null;
        } else {
            throw new MalformedPacketException("missing codr");
        }
    } else {
        codr = _json.getString("codr");
    }

    /**
     * rssi
     */
    if (!_json.has("rssi")) {
        throw new MalformedPacketException("missing rssi");
    } else {
        rssi = _json.getInt("rssi");
    }

    /**
     * lsnr
     */
    if (!_json.has("lsnr")) {
        if (modu.equals(Modulation.FSK)) {
            lsnr = Double.MAX_VALUE;
        } else {
            throw new MalformedPacketException("missing lsnr");
        }
    } else {
        lsnr = _json.getDouble("lsnr");
    }

    /**
     * size
     */
    if (!_json.has("size")) {
        throw new MalformedPacketException("missing size");
    } else {
        size = _json.getInt("size");
    }

    /**
     * data
     */
    if (!_json.has("data")) {
        throw new MalformedPacketException("missing data");
    } else {
        byte[] raw;

        try {
            raw = Base64.getDecoder().decode(_json.getString("data"));
        } catch (IllegalArgumentException ex) {
            throw new MalformedPacketException("malformed data");
        }

        data = new PhyPayload(ByteBuffer.wrap(raw));
    }
}