Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:net.openid.appauthdemo.TokenActivity.java

@MainThread
private void displayAuthorized() {
    findViewById(R.id.authorized).setVisibility(View.VISIBLE);
    findViewById(R.id.not_authorized).setVisibility(View.GONE);
    findViewById(R.id.loading_container).setVisibility(View.GONE);

    AuthState state = mStateManager.getCurrent();

    TextView refreshTokenInfoView = (TextView) findViewById(R.id.refresh_token_info);
    refreshTokenInfoView.setText((state.getRefreshToken() == null) ? R.string.no_refresh_token_returned
            : R.string.refresh_token_returned);

    TextView idTokenInfoView = (TextView) findViewById(R.id.id_token_info);
    idTokenInfoView/*from w  w  w. j  a  va2s  .co m*/
            .setText((state.getIdToken()) == null ? R.string.no_id_token_returned : R.string.id_token_returned);

    TextView accessTokenInfoView = (TextView) findViewById(R.id.access_token_info);
    if (state.getAccessToken() == null) {
        accessTokenInfoView.setText(R.string.no_access_token_returned);
    } else {
        Long expiresAt = state.getAccessTokenExpirationTime();
        if (expiresAt == null) {
            accessTokenInfoView.setText(R.string.no_access_token_expiry);
        } else if (expiresAt < System.currentTimeMillis()) {
            accessTokenInfoView.setText(R.string.access_token_expired);
        } else {
            String template = getResources().getString(R.string.access_token_expires_at);
            accessTokenInfoView.setText(String.format(template,
                    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZ").print(expiresAt)));
        }
    }

    Button refreshTokenButton = (Button) findViewById(R.id.refresh_token);
    refreshTokenButton.setVisibility(state.getRefreshToken() != null ? View.VISIBLE : View.GONE);
    refreshTokenButton.setOnClickListener((View view) -> refreshAccessToken());

    Button viewProfileButton = (Button) findViewById(R.id.view_profile);

    AuthorizationServiceDiscovery discoveryDoc = state.getAuthorizationServiceConfiguration().discoveryDoc;
    if (discoveryDoc == null || discoveryDoc.getUserinfoEndpoint() == null) {
        viewProfileButton.setVisibility(View.GONE);
    } else {
        viewProfileButton.setVisibility(View.VISIBLE);
        viewProfileButton.setOnClickListener((View view) -> fetchUserInfo());
    }

    ((Button) findViewById(R.id.sign_out)).setOnClickListener((View view) -> signOut());

    View userInfoCard = findViewById(R.id.userinfo_card);
    JSONObject userInfo = mUserInfoJson.get();
    if (userInfo == null) {
        userInfoCard.setVisibility(View.INVISIBLE);
    } else {
        try {
            String name = "???";
            if (userInfo.has("name")) {
                name = userInfo.getString("name");
            }
            ((TextView) findViewById(R.id.userinfo_name)).setText(name);

            if (userInfo.has("picture")) {
                Glide.with(TokenActivity.this).load(Uri.parse(userInfo.getString("picture"))).fitCenter()
                        .into((ImageView) findViewById(R.id.userinfo_profile));
            }

            ((TextView) findViewById(R.id.userinfo_json)).setText(mUserInfoJson.toString());
            userInfoCard.setVisibility(View.VISIBLE);
        } catch (JSONException ex) {
            Log.e(TAG, "Failed to read userinfo JSON", ex);
        }
    }
}

From source file:com.bindez.nlp.converter.RabbitConverter.java

public static String replace_with_rule(String rule, String output) {

    try {/*from w w  w  .  j a  va 2s .c o  m*/
        JSONArray rule_array = new JSONArray(rule);
        int max_loop = rule_array.length();

        //because of JDK 7 bugs in Android
        output = output.replace("null", "\uFFFF\uFFFF");

        for (int i = 0; i < max_loop; i++) {

            JSONObject obj = rule_array.getJSONObject(i);
            String from = obj.getString("from");
            String to = obj.getString("to");

            output = output.replaceAll(from, to);
            output = output.replace("null", "");

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

    output = output.replace("\uFFFF\uFFFF", "null");
    return output;
}

From source file:cn.ttyhuo.activity.InfoOwnerActivity.java

protected void setupViewOfHasLogin(JSONObject jObject) {
    try {/*from  www.  j a  v  a 2 s  . c  om*/

        ArrayList<String> pics = new ArrayList<String>();
        JSONArray jsonArray = jObject.optJSONArray("imageList");
        if (jsonArray != null) {
            for (int s = 0; s < jsonArray.length(); s++)
                pics.add(jsonArray.getString(s));
        }
        while (pics.size() < 3)
            pics.add("plus");
        mPicData = pics;
        mPicAdapter.updateData(pics);

        if (jObject.getBoolean("isTruckVerified")) {
            tv_edit_tips.setText("?????");
        } else if (jsonArray != null && jsonArray.length() > 2 && jObject.has("truckInfo")) {
            tv_edit_tips.setText(
                    "?????????");
        } else {
            tv_edit_tips.setText("??????");
        }

        if (jObject.has("truckInfo")) {
            JSONObject userJsonObj = jObject.getJSONObject("truckInfo");
            if (!userJsonObj.optString("licensePlate").isEmpty()
                    && userJsonObj.optString("licensePlate") != "null")
                mEditChepai.setText(userJsonObj.getString("licensePlate"));
            Integer truckType = userJsonObj.getInt("truckType");
            if (truckType != null && truckType > 0)
                mEditChexing.setText(ConstHolder.TruckTypeItems[truckType - 1]);
            else
                mEditChexing.setText("");
            if (!userJsonObj.optString("loadLimit").isEmpty() && userJsonObj.optString("loadLimit") != "null")
                mEditZaizhong.setText(userJsonObj.getString("loadLimit"));
            if (!userJsonObj.optString("truckLength").isEmpty()
                    && userJsonObj.optString("truckLength") != "null")
                mEditChechang.setText(userJsonObj.getString("truckLength"));
            if (!userJsonObj.optString("modelNumber").isEmpty()
                    && userJsonObj.optString("modelNumber") != "null")
                mEditXinghao.setText(userJsonObj.getString("modelNumber"));

            if (!userJsonObj.optString("seatingCapacity").isEmpty()
                    && userJsonObj.optString("seatingCapacity") != "null")
                mEditZuowei.setText(userJsonObj.getString("seatingCapacity"));
            if (!userJsonObj.optString("releaseYear").isEmpty()
                    && userJsonObj.optString("releaseYear") != "null")
                mEditDate.setText(userJsonObj.getString("releaseYear") + "");
            if (!userJsonObj.optString("truckWidth").isEmpty() && userJsonObj.optString("truckWidth") != "null")
                mEditKuan.setText(userJsonObj.getString("truckWidth"));
            if (!userJsonObj.optString("truckHeight").isEmpty()
                    && userJsonObj.optString("truckHeight") != "null")
                mEditGao.setText(userJsonObj.getString("truckHeight"));
        }

        if (!jObject.getBoolean("isTruckVerified")) {
            mEditChexing.setOnClickListener(this);
            mEditDate.setOnClickListener(this);
            mEditChepai.setFocusable(true);
            mEditChepai.setEnabled(true);
            mEditZaizhong.setFocusable(true);
            mEditZaizhong.setEnabled(true);
            mEditChechang.setFocusable(true);
            mEditChechang.setEnabled(true);
            mEditZuowei.setFocusable(true);
            mEditZuowei.setEnabled(true);
            mEditKuan.setFocusable(true);
            mEditKuan.setEnabled(true);
            mEditGao.setFocusable(true);
            mEditGao.setEnabled(true);
            mEditXinghao.setFocusable(true);
            mEditXinghao.setEnabled(true);
            canUpdate = true;
        } else {
            mPicGrid.setOnItemLongClickListener(null);

            mEditChepai.setFocusable(false);
            mEditChepai.setEnabled(false);
            mEditZaizhong.setFocusable(false);
            mEditZaizhong.setEnabled(false);
            mEditChechang.setFocusable(false);
            mEditChechang.setEnabled(false);
            mEditZuowei.setFocusable(false);
            mEditZuowei.setEnabled(false);
            mEditKuan.setFocusable(false);
            mEditKuan.setEnabled(false);
            mEditGao.setFocusable(false);
            mEditGao.setEnabled(false);
            mEditXinghao.setFocusable(false);
            mEditXinghao.setEnabled(false);
            canUpdate = false;
        }

        saveParams(true);

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

From source file:org.loklak.api.iot.ImportProfileServlet.java

private void doUpdate(Query post, HttpServletResponse response) throws IOException {
    String callback = post.get("callback", null);
    boolean jsonp = callback != null && callback.length() > 0;
    String data = post.get("data", "");
    if (data == null || data.length() == 0) {
        response.sendError(400, "your request must contain a data object.");
        return;/*from  w ww  .  ja  va  2 s. co m*/
    }

    // parse the json data
    boolean success;

    try {
        JSONObject json = null;
        try {
            json = new JSONObject(data);
        } catch (JSONException e) {
        }
        if (json == null) {
            throw new IOException("cannot parse json");
        }
        if (!json.has("id_str")) {
            throw new IOException("id_str field missing");
        }
        if (!json.has("source_type")) {
            throw new IOException("source_type field missing");
        }
        ImportProfileEntry i = DAO.SearchLocalImportProfiles(json.getString("id_str"));
        if (i == null) {
            throw new IOException("import profile id_str field '" + json.getString("id_str") + "' not found");
        }
        ImportProfileEntry importProfileEntry;
        try {
            importProfileEntry = new ImportProfileEntry(json);
        } catch (IllegalArgumentException e) {
            response.sendError(400, "Error updating import profile : " + e.getMessage());
            return;
        }
        importProfileEntry.setLastModified(new Date());
        success = DAO.writeImportProfile(importProfileEntry, true);
    } catch (IOException | NullPointerException e) {
        response.sendError(400, "submitted data is invalid : " + e.getMessage());
        Log.getLog().warn(e);
        return;
    }

    post.setResponse(response, "application/javascript");
    JSONObject json = new JSONObject(true);
    json.put("status", "ok");
    json.put("records", success ? 1 : 0);
    json.put("message", "updated");
    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(json.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:com.UAE.ibeaconreference.AppEngineClient.java

public String getTokenFromServer() {
    String s = null;//ww w .  j  a va  2  s.  c  om
    try {

        URL uri = new URL("https://rtonames.sprintlabs.io/token");

        Map<String, List<String>> headers = new HashMap<String, List<String>>();

        String key = "Authorization";
        String authStr = "6eece178-9fcf-45b7-ab50-08b8066daabe:e494a4e72b6f7c7672b74d311cbabf2672be8c24c9496554077936097195a5ac69b6acd11eb09a1ae07a40d2e7f0348d";
        String encoding = Base64.encodeToString(authStr.getBytes(), Base64.DEFAULT);
        encoding = encoding.replace("\n", "").replace("\r", "");

        System.out.println(encoding);
        List<String> value = Arrays.asList("Basic " + encoding);

        headers.put(key, value);

        AppEngineClient aec1 = new AppEngineClient();
        Request request = aec1.new GET(uri, headers);

        AsyncTask<Request, Void, Response> obj = new asyncclass().execute(request);

        Response response = obj.get();

        obj.cancel(true);

        obj = null;

        String body = null;
        try {
            body = new String(response.body, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        JSONObject tokenjson = AppEngineClient.getJSONObject(body);

        if (tokenjson.has("token")) {
            try {
                s = tokenjson.getString("token");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return s;
}

From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java

private JSONArray adjustTimeAndTipiSpecifici(String dataAsCSV) throws ParseException {
    JSONArray jsonArray = CDL.toJSONArray(dataAsCSV);
    int length = jsonArray.length();
    JSONArray jsonArrayNew = new JSONArray();
    for (int i = 0; i < length; i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);

        JSONObject jsonObjectNew = new JSONObject();

        jsonObjectNew.put("nome", jsonObject.getString("nome"));
        jsonObjectNew.put("indirizzo", jsonObject.getString("indirizzo"));
        jsonObjectNew.put("numeroCivico", jsonObject.getString("numero-civico"));
        jsonObjectNew.put("cap", jsonObject.getString("cap"));
        jsonObjectNew.put("quartiere", jsonObject.getString("quartiere"));
        jsonObjectNew.put("citta", jsonObject.getString("citta"));
        jsonObjectNew.put("geolocazione", jsonObject.getString("geolocazione"));
        jsonObjectNew.put("telefono", jsonObject.getString("telefono"));
        jsonObjectNew.put("mobile", jsonObject.getString("mobile"));
        jsonObjectNew.put("email", jsonObject.getString("email"));
        jsonObjectNew.put("web", jsonObject.getString("web"));
        jsonObjectNew.put("tipi", jsonObject.getString("tipi"));
        jsonObjectNew.put("tipiSpecifici", jsonObject.getString("tipi-specifici"));

        //         jsonObjectNew.put("tipiSpecificiReduced", getTipiReduced(jsonObject));
        //         jsonObjectNew.put("times", getTimes(jsonObject));

        LinkedList<String> date = findNumbers(jsonObject.getString("luogo-da-visitare.informazioni_storiche"));
        String dateString = date.toString().replace("[", "").replace("]", "");
        jsonObjectNew.put("luoghiDaVisitare.informazioniStoriche.date", dateString);

        jsonArrayNew.put(jsonObjectNew);
    }//from  w ww  .j  ava  2 s  .c o  m
    return jsonArrayNew;
}

From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java

private String getTipiReduced(JSONObject jsonObject) {
    String tipiSpecifici = jsonObject.getString("tipi-specifici");
    String tipiSpecificiReduced = "";
    switch (tipiSpecifici) {
    case "Discoteca":
        tipiSpecificiReduced = "Discoteca";
        break;//w  ww  .ja  v a2s .  c  o  m
    case "Pub, DiscoPub":
        tipiSpecificiReduced = "DiscoPub";
        break;
    case "Cocktail Bar":
        tipiSpecificiReduced = "Cocktail";
        break;
    case "Cocktail Bar, American Bar, Ristorante":
        tipiSpecificiReduced = "American";
        break;
    case "Cocktail Bar, Pizzeria, Ristorante, Panineria":
        tipiSpecificiReduced = "Panineria";
        break;
    case "Wine Bar, Pub":
        tipiSpecificiReduced = "Pub";
        break;
    case "Wine Bar":
        tipiSpecificiReduced = "Wine";
        break;
    default:
        tipiSpecificiReduced = "";
        break;
    }
    return tipiSpecificiReduced;
}

From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java

private JSONArray getTimes(JSONObject jsonObject) throws ParseException {
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    String date = "1970-01-01";
    JSONArray times = new JSONArray();
    String apertura = jsonObject.getString("apertura");
    long startingTimeEpoch = 0;
    if (apertura.isEmpty())
        apertura = "19.00"; // default
    startingTimeEpoch = sdf.parse(date + " " + apertura.replace(".", ":")).getTime();

    String chiusura = jsonObject.getString("chiusura");
    long endingTimeEpoch = 0;
    if (chiusura.isEmpty())
        chiusura = "1.00"; // default
    double parsedEndingTime = Double.parseDouble(chiusura);
    if (parsedEndingTime >= 0f && parsedEndingTime < 6f) // we are in next day
        date = "1970-01-02";
    endingTimeEpoch = sdf.parse(date + " " + chiusura.replace(".", ":")).getTime();

    String startingTimeEpoched = "" + startingTimeEpoch;
    String endingTimeEpoched = "" + endingTimeEpoch;
    JSONObject et = new JSONObject();
    et.put("starting_time", startingTimeEpoched);
    et.put("ending_time", endingTimeEpoched);
    times.put(et);/*  w  w w .j  a  va 2  s .  c o  m*/

    return times;
}

From source file:net.zorgblub.typhon.dto.PageOffsets.java

public static PageOffsets fromJSON(String json) throws JSONException {
    JSONObject offsetsObject = new JSONObject(json);
    PageOffsets result = new PageOffsets();

    result.fontFamily = offsetsObject.getString(Fields.fontFamily.name());
    result.fontSize = offsetsObject.getInt(Fields.fontSize.name());
    result.vMargin = offsetsObject.getInt(Fields.vMargin.name());
    result.hMargin = offsetsObject.getInt(Fields.hMargin.name());
    result.lineSpacing = offsetsObject.getInt(Fields.lineSpacing.name());
    result.fullScreen = offsetsObject.getBoolean(Fields.fullScreen.name());
    result.algorithmVersion = offsetsObject.optInt(Fields.algorithmVersion.name(), -1);
    result.allowStyling = offsetsObject.optBoolean(Fields.allowStyling.name(), true);

    result.offsets = readOffsets(offsetsObject.getJSONArray(Fields.offsets.name()));

    return result;
}

From source file:be.brunoparmentier.openbikesharing.app.parsers.BikeNetworksListParser.java

public BikeNetworksListParser(String toParse) throws ParseException {
    bikeNetworks = new ArrayList<>();

    try {//from  w w w  .j  a va 2 s.c  om
        JSONObject jsonObject = new JSONObject(toParse);
        JSONArray rawNetworks = jsonObject.getJSONArray("networks");
        for (int i = 0; i < rawNetworks.length(); i++) {
            JSONObject rawNetwork = rawNetworks.getJSONObject(i);

            String id = rawNetwork.getString("id");
            String name = rawNetwork.getString("name");
            String company = rawNetwork.getString("company");
            BikeNetworkLocation location;

            /* network location */
            {
                JSONObject rawLocation = rawNetwork.getJSONObject("location");

                double latitude = rawLocation.getDouble("latitude");
                double longitude = rawLocation.getDouble("longitude");
                String city = rawLocation.getString("city");
                String country = rawLocation.getString("country");

                location = new BikeNetworkLocation(latitude, longitude, city, country);

            }
            bikeNetworks.add(new BikeNetworkInfo(id, name, company, location));
        }
    } catch (JSONException e) {
        throw new ParseException("Error parsing JSON", 0);
    }
}