Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:com.mifos.mifosxdroid.dialogfragments.loanchargedialog.LoanChargeDialogFragment.java

@Override
public void showAllChargesV3(ResponseBody result) {

    /* Activity is null - Fragment has been detached; no need to do anything. */
    if (getActivity() == null)
        return;//from w  ww.  j  a v  a  2  s. c om

    Log.d(LOG_TAG, "");

    final List<Charges> charges = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> chargesNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("chargeOptions")) {
            JSONArray chargesTypes = obj.getJSONArray("chargeOptions");
            for (int i = 0; i < chargesTypes.length(); i++) {
                JSONObject chargesObject = chargesTypes.getJSONObject(i);
                Charges charge = new Charges();
                charge.setId(chargesObject.optInt("id"));
                charge.setName(chargesObject.optString("name"));
                charges.add(charge);
                chargesNames.add(chargesObject.optString("name"));
                chargeNameIdHashMap.put(charge.getName(), charge.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> chargesAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item, chargesNames);
    chargesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_charge_name.setAdapter(chargesAdapter);
    sp_charge_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Id = chargeNameIdHashMap.get(chargesNames.get(i));
            Log.d("chargesoptionss" + chargesNames.get(i), String.valueOf(Id));
            if (Id != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_charge), Toast.LENGTH_SHORT)
                        .show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

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

public Txpk(JSONObject _json) throws MalformedPacketException {

    /**/*  w  w w  .  j  av a  2s  .  com*/
     * imme
     */
    if (!_json.has("imme")) {
        imme = false;
    } else {
        imme = _json.getBoolean("imme");
    }

    /**
     * tmst
     */
    if (!_json.has("tmst")) {
        tmst = Integer.MAX_VALUE;
    } else {
        tmst = _json.getInt("tmst");
    }

    /**
     * time
     */
    if (!_json.has("time")) {
        time = null;
    } else {
        time = _json.getString("time");
    }

    /**
     * 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");
    }

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

    /**
     * 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");
    }

    /**
     * fdev
     */
    if (!_json.has("fdev")) {
        if (modu.equals(Modulation.LORA)) {
            fdev = Integer.MAX_VALUE;
        } else {
            throw new MalformedPacketException("missing fdev");
        }
    } else {
        fdev = _json.getInt("fdev");
    }

    /**
     * ipol
     */
    if (!_json.has("ipol")) {
        if (modu.equals(Modulation.FSK)) {
            ipol = false;
        } else {
            throw new MalformedPacketException("missing ipol");
        }
    } else {
        ipol = _json.getBoolean("ipol");
    }

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

    /**
     * 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));
    }

    /**
     * ncrc
     */
    if (!_json.has("ncrc")) {
        ncrc = false;
    } else {
        ncrc = _json.getBoolean("ncrc");
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.ImageViewerActivity.java

@Override
public void onResume() {
    super.onResume();
    if (mIntent.hasExtra("image_url")) {
        String url = mIntent.getStringExtra("image_url");
        ((App) getApplication()).objectImages.lazyLoadImage(url.hashCode(), Uri.parse(url), im);
        bitmap = mgr.getBitmap(url.hashCode(), url);
    } else if (mIntent.hasExtra("b64Bytes")) {
        String b64Bytes = mIntent.getStringExtra("b64Bytes");
        ((App) getApplication()).objectImages.lazyLoadImage(b64Bytes.hashCode(), b64Bytes, im);
        bitmap = mgr.getBitmapB64(b64Bytes.hashCode(), b64Bytes);
    } else if (mIntent.hasExtra("bytes")) {
        byte[] bytes = mIntent.getByteArrayExtra("bytes");
        ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im);
        bitmap = mgr.getBitmap(bytes.hashCode(), bytes);
    } else if (mIntent.hasExtra("obj")) {
        try {//from  www . j  a  v a 2s.  c  om
            final JSONObject content = new JSONObject(mIntent.getStringExtra("obj"));
            byte[] bytes = FastBase64.decode(content.optString(PictureObj.DATA));
            ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im);
            bitmap = mgr.getBitmap(bytes.hashCode(), bytes);
        } catch (JSONException e) {
        }
    }

    if (mIntent.hasExtra("objHash")) {
        if (!ContentCorral.CONTENT_CORRAL_ENABLED) {
            return;
        }

        long objHash = mIntent.getLongExtra("objHash", -1);
        final DbObj obj = App.instance().getMusubi().objForHash(objHash);
        final JSONObject json = obj.getJson();
        if (json.has(CorralClient.OBJ_LOCAL_URI)) {
            // TODO: this is a proof-of-concept.
            new Thread() {
                public void run() {
                    try {
                        if (!mCorralClient.fileAvailableLocally(obj)) {
                            //toast("Trying to go HD...");
                        }
                        // Log.d(TAG, "Trying to go HD...");
                        final Uri fileUri = mCorralClient.fetchContent(obj);
                        if (fileUri == null) {
                            try {
                                Log.d(TAG, "Failed to go HD for " + json.getString(CorralClient.OBJ_LOCAL_URI));
                            } catch (JSONException e) {
                                Log.d(TAG, "Failed to go HD for " + json);
                            }
                            return;
                        }
                        // Log.d(TAG, "Opening HD file " + fileUri);

                        InputStream is = getContentResolver().openInputStream(fileUri);
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 4;

                        Matrix matrix = new Matrix();
                        float rotation = PhotoTaker.rotationForImage(ImageViewerActivity.this, fileUri);
                        if (rotation != 0f) {
                            matrix.preRotate(rotation);
                        }
                        bitmap = BitmapFactory.decodeStream(is, null, options);

                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                im.setImageBitmap(bitmap);
                            }
                        });
                    } catch (IOException e) {
                        // toast("Failed to go HD");
                        Log.e(TAG, "Failed to get hd content", e);
                        // continue
                    }
                };
            }.start();
        }
    }
}

From source file:com.nginious.http.application.Http11SerializerTestCase.java

private void testResponse(String body) throws Exception {
    JSONObject bean = new JSONObject(body);
    assertTrue(bean.has("testBean1"));
    bean = bean.getJSONObject("testBean1");

    assertEquals(true, bean.getBoolean("first"));
    assertEquals(1.1d, bean.getDouble("second"));
    assertEquals(1.2f, (float) bean.getDouble("third"));
    assertEquals(2, bean.getInt("fourth"));
    assertEquals(5L, bean.getLong("fifth"));
    assertEquals((short) 3, (short) bean.getInt("sixth"));
    assertEquals("Seven", bean.getString("seventh"));
    assertTrue(bean.has("eight"));
    assertTrue(bean.has("ninth"));
}

From source file:net.cellcloud.talk.HttpSpeaker.java

@Override
public boolean speak(String celletIdentifier, Primitive primitive) {
    if (this.state != SpeakerState.CALLED || !this.client.isStarted()) {
        return false;
    }//from w ww  .  ja  v  a  2  s  .  c o  m

    JSONObject json = new JSONObject();
    try {
        // ? Tag
        json.put(HttpDialogueHandler.Tag, Nucleus.getInstance().getTagAsString());
        //  JSON
        JSONObject primJSON = new JSONObject();
        PrimitiveSerializer.write(primJSON, primitive);
        json.put(HttpDialogueHandler.Primitive, primJSON);
        // Cellet
        json.put(HttpDialogueHandler.Identifier, celletIdentifier);
    } catch (JSONException e) {
        Logger.log(this.getClass(), e, LogLevel.ERROR);
        return false;
    }

    // URL
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_DIALOGUE);

    // ?
    StringContentProvider content = new StringContentProvider(json.toString(), "UTF-8");
    try {
        // ??
        ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.POST)
                .header(HttpHeader.COOKIE, this.cookie).content(content).send();
        if (response.getStatus() == HttpResponse.SC_OK) {
            // ????
            // ?
            JSONObject data = this.readContent(response.getContent());
            if (data.has(HttpDialogueHandler.Queue)) {
                int size = data.getInt(HttpDialogueHandler.Queue);
                if (size > 0) {
                    //  Tick 
                    this.hbTick = 0;

                    TalkService.getInstance().executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            requestHeartbeat();
                        }
                    });
                }
            }
        } else {
            Logger.w(this.getClass(), "Send dialogue data failed : " + response.getStatus());
        }
    } catch (InterruptedException | TimeoutException | ExecutionException e) {
        return false;
    } catch (JSONException e) {
        return false;
    }

    url = null;

    return true;
}

From source file:net.cellcloud.talk.HttpSpeaker.java

private void requestHeartbeat() {
    //  URL// w w w .j a va2  s  .  co  m
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_HEARTBEAT);

    // ??
    try {
        ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.GET)
                .header(HttpHeader.COOKIE, this.cookie).send();
        if (response.getStatus() == HttpResponse.SC_OK) {
            // 
            this.hbFailedCounts = 0;

            JSONObject responseData = this.readContent(response.getContent());
            if (responseData.has(HttpHeartbeatHandler.Primitives)) {
                // ?
                JSONArray primitives = responseData.getJSONArray(HttpHeartbeatHandler.Primitives);
                for (int i = 0, size = primitives.length(); i < size; ++i) {
                    JSONObject primJSON = primitives.getJSONObject(i);
                    // ??
                    this.doDialogue(primJSON);
                }
            }
        } else {
            // 
            ++this.hbFailedCounts;
            Logger.w(HttpSpeaker.class, "Heartbeat failed");
        }
    } catch (InterruptedException | TimeoutException | ExecutionException e) {
        // 
        ++this.hbFailedCounts;
    } catch (JSONException e) {
        Logger.log(getClass(), e, LogLevel.ERROR);
    }

    // hbMaxFailed ?
    if (this.hbFailedCounts >= this.hbMaxFailed) {
        this.hangUp();
    }
}

From source file:org.loklak.android.client.SearchClient.java

public static Timeline search(final String protocolhostportstub, final String query, final Timeline.Order order,
        final String source, final int count, final int timezoneOffset, final long timeout) throws IOException {
    Timeline tl = new Timeline(order);
    String urlstring = "";
    try {//from  w w  w  .  ja  va  2s. c  o m
        urlstring = protocolhostportstub + "/api/search.json?q="
                + URLEncoder.encode(query.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset
                + "&maximumRecords=" + count + "&source=" + (source == null ? "all" : source)
                + "&minified=true&timeout=" + timeout;
        JSONObject json = JsonIO.loadJson(urlstring);
        if (json == null || json.length() == 0)
            return tl;
        JSONArray statuses = json.getJSONArray("statuses");
        if (statuses != null) {
            for (int i = 0; i < statuses.length(); i++) {
                JSONObject tweet = statuses.getJSONObject(i);
                JSONObject user = tweet.getJSONObject("user");
                if (user == null)
                    continue;
                tweet.remove("user");
                UserEntry u = new UserEntry(user);
                MessageEntry t = new MessageEntry(tweet);
                tl.add(t, u);
            }
        }
        if (json.has("search_metadata")) {
            JSONObject metadata = json.getJSONObject("search_metadata");
            if (metadata.has("hits")) {
                tl.setHits((Integer) metadata.get("hits"));
            }
            if (metadata.has("scraperInfo")) {
                String scraperInfo = (String) metadata.get("scraperInfo");
                tl.setScraperInfo(scraperInfo);
            }
        }
    } catch (Throwable e) {
        Log.e("SeachClient", e.getMessage(), e);
    }
    //System.out.println(parser.text());
    return tl;
}

From source file:com.skalski.raspberrycontrol.Activity_GPIO.java

Handler getClientHandler() {

    return new Handler() {
        @Override/*w  ww .ja va2 s  .  c om*/
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            JSONArray gpios;
            gpioArray = new ArrayList<Custom_GPIOAdapter>();
            gpioLayout.setRefreshing(false);

            Log.i(LOGTAG, LOGPREFIX + "new message received from server");

            try {

                root = new JSONObject(msg.obj.toString());

                if (root.has(TAG_ERROR)) {

                    String err = getResources().getString(R.string.com_msg_3) + root.getString(TAG_ERROR);
                    Log.e(LOGTAG, LOGPREFIX + root.getString(TAG_ERROR));
                    toast_connection_error(err);

                } else {

                    gpios = root.getJSONArray(TAG_GPIOSTATE);

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

                        JSONObject gpioss = gpios.getJSONObject(i);

                        int gpio = gpioss.getInt(TAG_GPIO);
                        int value = gpioss.getInt(TAG_VALUE);
                        String direction = gpioss.getString(TAG_DIRECTION);

                        gpioArray.add(new Custom_GPIOAdapter(gpio, value, direction));
                    }

                    if (gpios.length() == 0) {
                        Log.w(LOGTAG, LOGPREFIX + "can't find exported GPIO's on server side");
                        toast_connection_error(getResources().getString(R.string.error_msg_8));
                    }

                    if (gpioPinout.getDrawable().getConstantState() == getResources()
                            .getDrawable(R.drawable.gpio_unknown).getConstantState()) {
                        if (root.has(TAG_REVISION)) {
                            String revision;
                            revision = root.getString(TAG_REVISION);

                            Log.i(LOGTAG, LOGPREFIX + "set new GPIO layout image");

                            if (revision.equals("0002") || revision.equals("0003")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_1);

                            } else if (revision.equals("0004") || revision.equals("0005")
                                    || revision.equals("0006") || revision.equals("0007")
                                    || revision.equals("0008") || revision.equals("0009")
                                    || revision.equals("000d") || revision.equals("000e")
                                    || revision.equals("000f")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_2);

                            } else if (revision.equals("0010") || revision.equals("0011")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_3);

                            } else {
                                Log.wtf(LOGTAG, LOGPREFIX + "your Raspberry Pi board is weird");
                            }
                        }
                    }
                }

            } catch (Exception ex) {
                Log.e(LOGTAG, LOGPREFIX + "received invalid JSON object");
                toast_connection_error(getResources().getString(R.string.error_msg_2));
            }

            setListAdapter(new Custom_GPIOArrayAdapter(getApplicationContext(), gpioArray));
        }
    };
}

From source file:gr.cti.android.experimentation.controller.ui.RestDataController.java

@ResponseBody
@RequestMapping(value = "/data", method = RequestMethod.GET, produces = "text/csv")
public String dataCsv(@RequestParam(value = "type") final String type) throws JSONException {
    final StringBuilder response = new StringBuilder();
    for (final Result result : resultRepository.findAll()) {
        try {//from  w ww  .j  a  v  a  2  s .c  om
            final JSONObject object = new JSONObject(result.getMessage());
            if (object.has(type)) {
                response.append(object.get(type)).append("\n");
            }
        } catch (Exception ignore) {
        }
    }
    return response.toString();
}

From source file:com.vk.sdk.api.VKRequest.java

public VKAbstractOperation getOperation() {
    if (this.parseModel) {
        if (this.mModelClass != null) {
            mLoadingOperation = new VKModelOperation(getPreparedRequest(), this.mModelClass);
        } else if (this.mModelParser != null) {
            mLoadingOperation = new VKModelOperation(getPreparedRequest(), this.mModelParser);
        }/*from  www  .ja  va  2 s.com*/
    }
    if (mLoadingOperation == null)
        mLoadingOperation = new VKJsonOperation(getPreparedRequest());
    ((VKJsonOperation) mLoadingOperation).setJsonOperationListener(new VKJSONOperationCompleteListener() {
        @Override
        public void onComplete(VKJsonOperation operation, JSONObject response) {
            if (response.has("error")) {
                try {
                    VKError error = new VKError(response.getJSONObject("error"));
                    if (VKSdk.DEBUG && VKSdk.DEBUG_API_ERRORS) {
                        Log.w(VKSdk.SDK_TAG, operation.getResponseString());
                    }
                    if (processCommonError(error))
                        return;
                    provideError(error);
                } catch (JSONException e) {
                    if (VKSdk.DEBUG)
                        e.printStackTrace();
                }

                return;
            }
            provideResponse(response,
                    mLoadingOperation instanceof VKModelOperation
                            ? ((VKModelOperation) mLoadingOperation).parsedModel
                            : null);
        }

        @Override
        public void onError(VKJsonOperation operation, VKError error) {
            //??? ??? ???????? ????, ??? ????????? ??????????? ????? ??? ??????? ????????
            if (error.errorCode != VKError.VK_CANCELED && error.errorCode != VKError.VK_API_ERROR
                    && operation != null && operation.response != null
                    && operation.response.getStatusLine().getStatusCode() == 200) {
                provideResponse(operation.getResponseJson(), null);
                return;
            }
            if (VKSdk.DEBUG && VKSdk.DEBUG_API_ERRORS && operation != null
                    && operation.getResponseString() != null) {
                Log.w(VKSdk.SDK_TAG, operation.getResponseString());
            }
            if (attempts == 0 || ++mAttemptsUsed < attempts) {
                if (requestListener != null)
                    requestListener.attemptFailed(VKRequest.this, mAttemptsUsed, attempts);
                runOnLooper(new Runnable() {
                    @Override
                    public void run() {
                        start();
                    }
                }, 300);
                return;
            }
            provideError(error);
        }
    });
    return mLoadingOperation;
}