Java Code Examples for org.json.JSONObject.has()

The following are Jave code examples for showing how to use has() of the org.json.JSONObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: chromium-for-android-56-debug-video   File: CastMessageHandler.java   View Source Code Vote up 8 votes
/**
 * Modifies the received MediaStatus message to match the format expected by the client.
 */
private void sanitizeMediaStatusMessage(JSONObject object) throws JSONException {
    object.put("sessionId", mSession.getSessionId());

    JSONArray mediaStatus = object.getJSONArray("status");
    for (int i = 0; i < mediaStatus.length(); ++i) {
        JSONObject status = mediaStatus.getJSONObject(i);
        status.put("sessionId", mSession.getSessionId());
        if (!status.has("supportedMediaCommands")) continue;

        JSONArray commands = new JSONArray();
        int bitfieldCommands = status.getInt("supportedMediaCommands");
        for (int j = 0; j < 4; ++j) {
            if ((bitfieldCommands & (1 << j)) != 0) {
                commands.put(MEDIA_SUPPORTED_COMMANDS[j]);
            }
        }

        status.put("supportedMediaCommands", commands);  // Removes current entry.
    }
}
 
Example 2
Project: GcmForMojo   File: HwPushReceiver.java   View Source Code Vote up 7 votes
@Override
public boolean onPushMsg(Context context, byte[] msg, Bundle bundle) {

    try {
        String remoteMessageOrign = new String(msg, "UTF-8");
        JSONObject remoteMessage = new JSONObject(remoteMessageOrign);

        if(!remoteMessage.has("isAt")) remoteMessage.put("isAt","0");
        if(!remoteMessage.has("senderType")) remoteMessage.put("senderType","1");

        //SharedPreferences Settings =        context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
        String tokenSender = mySettings.getString("push_type","GCM");

        if(tokenSender.equals("HwPush")) {
            Log.d(MYTAG, "华为推送:"+remoteMessageOrign);
            MessageUtil.MessageUtilDo(context,remoteMessage.getString("msgId"),remoteMessage.getString("type"),remoteMessage.getString("senderType"),remoteMessage.getString("title"),remoteMessage.getString("message"),remoteMessage.getString("isAt"));
        }

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

}
 
Example 3
Project: JHearthstone   File: Player.java   View Source Code Vote up 7 votes
public void deapplyAura(JSONObject aura, Player player, int min) {
	String auraClass = "";
	if (aura.has("class")) {
		auraClass = aura.getString("class");
	}
	if (auraClass.equals("BuffAura")) {
		int attackBonus = 0;
		int hpBonus = 0;
		if (aura.has("attackBonus")) {
			attackBonus = aura.getInt("attackBonus");
		}
		if (aura.has("hpBonus")) {
			hpBonus = aura.getInt("hpBonus");
		}
		System.out.println("ATTACK BONUS:" + attackBonus + ", HEALTH BONUS: " + hpBonus);
		game.players.get(game.players.indexOf(player)).board.get(min).setAttack(player.board.get(min).getAttack() - attackBonus);
		game.players.get(game.players.indexOf(player)).board.get(min).setMaxHealth(game.players.get(game.players.indexOf(player)).board.get(min).getMaxHealth() - hpBonus);
		if (game.players.get(game.players.indexOf(player)).board.get(min).getHealth() <= 0) {
			game.players.get(game.players.indexOf(player)).board.get(min).setHealth(1);
		}
		game.players.get(game.players.indexOf(player)).board.get(min).setHealth(game.players.get(game.players.indexOf(player)).board.get(min).getHealth() - hpBonus);
	}
}
 
Example 4
Project: xlight_android_native   File: ParticleCloudException.java   View Source Code Vote up 7 votes
private String loadServerErrorMsg() {
    if (responseData == null || responseData.getBody() == null) {
        return null;
    }
    try {
        JSONObject jsonObject = new JSONObject(responseData.getBody());

        if (jsonObject.has("error_description")) {
            return jsonObject.getString("error_description");

        } else if (jsonObject.has("errors")) {
            List<String> errors = getErrors(jsonObject);
            return errors.isEmpty() ? null : ParticleInternalStringUtils.join(errors, '\n');

        } else if (jsonObject.has("error")) {
            return jsonObject.getString("error");
        }

    } catch (JSONException e) {
    }
    return null;
}
 
Example 5
Project: hyperrail-for-android   File: IrailApiParser.java   View Source Code Vote up 6 votes
@Override
public Disturbance[] parseDisturbances(JSONObject jsonData) throws JSONException {

    if (jsonData == null) {
        throw new IllegalArgumentException("JSONObject is null");
    }

    if (!jsonData.has("disturbance")) {
        return new Disturbance[0];
    }

    JSONArray items = jsonData.getJSONArray("disturbance");

    Disturbance[] result = new Disturbance[items.length()];

    for (int i = 0; i < items.length(); i++) {
        result[i] = new Disturbance(i,
                timestamp2date(items.getJSONObject(i).getString("timestamp")),
                items.getJSONObject(i).getString("title"),
                items.getJSONObject(i).getString("description"),
                items.getJSONObject(i).getString("link"));
    }

    return result;
}
 
Example 6
Project: keemob   File: FileUtils.java   View Source Code Vote up 6 votes
private boolean needPermission(String nativeURL, int permissionType) throws JSONException {
    JSONObject j = requestAllPaths();
    ArrayList<String> allowedStorageDirectories = new ArrayList<String>();
    allowedStorageDirectories.add(j.getString("applicationStorageDirectory"));
    if(j.has("externalApplicationStorageDirectory")) {
        allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory"));
    }

    if(permissionType == READ && hasReadPermission()) {
        return false;
    }
    else if(permissionType == WRITE && hasWritePermission()) {
        return false;
    }

    // Permission required if the native url lies outside the allowed storage directories
    for(String directory : allowedStorageDirectories) {
        if(nativeURL.startsWith(directory)) {
            return false;
        }
    }
    return true;
}
 
Example 7
Project: kolibri-android   File: RuntimeConfig.java   View Source Code Vote up 6 votes
RuntimeConfig(@NonNull JSONObject json, String url) {
  runtime = json;

  final String applicationId = Uri.parse(url).getPathSegments().get(1);
  final boolean isAssetsExternal = json.has("amazon");

  formattedAssetUrl = isAssetsExternal
      ? json.optString("amazon") + "/apps/" + applicationId + "/assets/%s.png"
      : url.replace("runtime", "assets") + "/%s/download";

  if (json.length() == 0) {
    throw new KolibriException("Runtime config JSON is empty. Cannot construct configuration.");
  }

  parseStructure();

  if (navigation == null || domain == null || scheme == null || styling == null) {
    throw new KolibriException("Runtime config JSON is not valid one.");
  }
}
 
Example 8
Project: WordLing   File: WordpackParser.java   View Source Code Vote up 6 votes
public boolean validateJSONWordpack(String text) {
    try {
        JSONObject jsonData = new JSONObject(text);
        if (jsonData.has("from") &&
                jsonData.has("to") &&
                jsonData.has("pack") &&
                jsonData.has("title")) {
            if (jsonData.getJSONArray("pack").length()>0) return true;
        } else
            Log.v("WordLing", "Invalid wordpack format");


    } catch (JSONException e) {
        Log.v("WordLing", "Error occured when parsing wordpack");
    }
    return false;
}
 
Example 9
Project: CatchSpy   File: SettingsActivity.java   View Source Code Vote up 5 votes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Config.REQUEST_GET_LOCAL_DICTIONARY) {
        if (resultCode == RESULT_OK) {
            if (data != null && data.getData() != null) {
                ContentResolver resolver = getContentResolver();
                String fileType = resolver.getType(data.getData());
                if (fileType != null) {
                    if (fileType.startsWith("image")) {
                        Toast.makeText(this, R.string.settings_extra_words_load_failed, Toast.LENGTH_SHORT).show();
                        finish();
                        return;
                    }
                }
                String file_path = URI.getAbsolutePath(this, data.getData());
                String text = IOMethod.readFile(file_path);
                try {
                    JSONObject jsonObject = new JSONObject(text);
                    if (jsonObject.has(Config.DEFAULT_EXTRA_WORDS_DATA_NAME)) {
                        String name = new File(file_path).getName();
                        String path = Config.DEFAULT_APPLICATION_DATA_DIR + name;
                        if (IOMethod.writeFile(jsonObject.toString(), path)) {
                            String newName = Code.unicodeEncode(name) + "-" + Code.getFileMD5String(path);
                            if (IOMethod.renameFile(path, newName)) {
                                Toast.makeText(this, R.string.settings_extra_words_load_success, Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Toast.makeText(this, R.string.settings_extra_words_load_failed, Toast.LENGTH_SHORT).show();
            }
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 10
Project: CF-rating-prediction   File: PastRatingDownloader.java   View Source Code Vote up 5 votes
private static Map<String, Integer> toMap(JSONObject json) {
    if (!json.has("status") || !json.has(JSON_RESULTS)) {
        return new HashMap<>();
    }

    Map<String, Integer> ratings = new HashMap<>();
    JSONArray ratingsArray = json.getJSONArray(JSON_RESULTS);
    for (Object rating : ratingsArray) {
        JSONObject r = (JSONObject) rating;
        ratings.put(r.getString("handle"), r.getInt("rating"));
    }

    return ratings;
}
 
Example 11
Project: J-Cord   File: GuildCreateEventHandler.java   View Source Code Vote up 5 votes
@Override
public void dispatchEvent(JSONObject json, int sequence) {

    Guild guild = (Guild) identity.getGuild(json.getString("id"));

    if (json.has("presences")) {
        JSONArray presences = json.getJSONArray("presences");

        for (int i = 0; i < presences.length(); i++) {
            JSONObject presence = presences.getJSONObject(i);
            builder.buildPresence(presence, (User) identity.getUser(presence.getJSONObject("user").getString("id")));  // Presences are set automatically
        }
    }

    // Ignore initial guild create event
    if (guild == null) {
        guild = builder.buildGuild(json);
        dispatchEvent(new GuildCreateEvent(identity, sequence, guild));
    }

    // Request guild members after the guild is built
    long memberCount = json.getLong("member_count");
    if (memberCount > JCord.GUILD_MEMBERS_LARGE_THRESHOLD) { // Need to request guild members
        identity.getGateway().sendRequestMembers(json.getString("id"));
    }

}
 
Example 12
Project: s-store   File: ProfileMeasurement.java   View Source Code Vote up 5 votes
@Override
public void fromJSON(JSONObject json_object, Database catalog_db) throws JSONException {
    this.name = json_object.getString("NAME");
    this.total_time = json_object.getLong("TIME");
    this.invocations = json_object.getInt("INVOCATIONS");
    if (json_object.has("HISTORY")) {
        this.history = null;
        this.enableHistoryTracking();
        JSONArray json_arr = json_object.getJSONArray("HISTORY");
        for (int i = 0, cnt = json_arr.length(); i < cnt; i++) {
            this.history.add(json_arr.getLong(i));
        } // FOR
    }
}
 
Example 13
Project: marathonv5   File: JavaFXTreeTableViewElement.java   View Source Code Vote up 5 votes
private List<IJavaFXElement> findSelectByProperties(JSONObject o) {
    List<IJavaFXElement> r = new ArrayList<>();
    if (o.has("select")) {
        JSONObject jo = new JSONObject((String) o.get("select"));
        JSONArray cell = (JSONArray) jo.get("cell");
        JavaFXTreeTableViewCellElement e = new JavaFXTreeTableViewCellElement(this, cell.getString(0),
                getTreeTableColumnIndex((TreeTableView<?>) getComponent(), cell.getString(1)));
        if (!(boolean) e._makeVisible()) {
            return Arrays.asList();
        }
        r.add(e);
    }
    return r;
}
 
Example 14
Project: boohee_v5.6   File: Milestone.java   View Source Code Vote up 5 votes
public static ArrayList<Milestone> parseLists(JSONObject object) {
    if (!object.has("achieved_milestones")) {
        return null;
    }
    return (ArrayList) new Gson().fromJson(object.optString("achieved_milestones"), new
            TypeToken<ArrayList<Milestone>>() {
    }.getType());
}
 
Example 15
Project: LiuAGeAndroid   File: ArticleListBean.java   View Source Code Vote up 5 votes
public ArticleListBean(JSONObject article) {
    try {
        classid = article.getString("classid");
        if (article.has("classname")) {
            classname = article.getString("classname");
        }
        id = article.getString("id");
        title = article.getString("title");
        befrom = article.getString("befrom");
        onclick = article.getString("onclick");
        isgood = article.getString("isgood");
        istop = article.getString("istop");
        firsttitle = article.getString("firsttitle");
        isurl = article.getString("isurl");
        keyboard = article.getString("keyboard");
        if (article.has("titleurl")) {
            titleurl = article.getString("titleurl");
        }
        plnum = article.getString("plnum");
        newstime = article.getString("newstime");
        titlepic = article.getString("titlepic");
        JSONArray morepicArray = article.getJSONArray("morepic");
        morepic = new String[morepicArray.length()];
        for (int j = 0; j < morepicArray.length(); j++) {
            morepic[j] = morepicArray.get(j).toString();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 16
Project: youkes_browser   File: JSONUtil.java   View Source Code Vote up 5 votes
public static int getInt(JSONObject docObj, String name) {
	int ret = 0;

	if (docObj.has(name)) {
		try {
			ret = docObj.getInt(name);
		} catch (JSONException e) {

		}
	}

	return ret;
}
 
Example 17
Project: KotlinStudy   File: VocalVerifyDemo.java   View Source Code Vote up 5 votes
@Override
public void onResult(IdentityResult result, boolean islast) {
	Log.d(TAG, result.getResultString());
	mAuthidEditText.setEnabled(false);//密码获取成功后,authid不可再变动

	mProDialog.dismiss();
	btn_start_record.setClickable(true);
	switch (mPwdType) {
		case PWD_TYPE_NUM:
			StringBuffer numberString = new StringBuffer();
			try {
				JSONObject object = new JSONObject(result.getResultString());
				if (!object.has("num_pwd")) {
					mNumPwd = null;
					return;
				}

				JSONArray pwdArray = object.optJSONArray("num_pwd");
				numberString.append(pwdArray.get(0));
				for (int i = 1; i < pwdArray.length(); i++) {
					numberString.append("-" + pwdArray.get(i));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			mNumPwd = numberString.toString();
			mNumPwdSegs = mNumPwd.split("-");

			mResultEditText.setText("您的注册密码:\n" + mNumPwd + "\n请长按“按住说话”按钮进行注册\n");
			break;
		default:
			break;
	}
}
 
Example 18
Project: letv   File: CommonParser.java   View Source Code Vote up 4 votes
public boolean has(JSONObject jsonObject, String name) {
    return jsonObject.has(name);
}
 
Example 19
Project: logistimo-web-service   File: ReplenishmentReportService.java   View Source Code Vote up 4 votes
@Override
public TableResponseModel buildReportTableData(String json, ReportViewType viewType,
                                               QueryRequestModel model) throws Exception {
  JSONObject jsonObject = new JSONObject(json);
  if (!jsonObject.has(HEADINGS)) {
    xLogger.warn("No data found");
    return null;
  }
  JSONArray headersJson = jsonObject.getJSONArray(HEADINGS);
  if (headersJson.length() < 3) {
    xLogger.warn("Insufficient data found. Expect to have at least 3 columns");
    return null;
  }
  jsonObject = constructTableBaseData(jsonObject, viewType, headersJson, model);
  if (jsonObject.has(TABLE) && jsonObject.getJSONObject(TABLE).length() != 0) {
    TableResponseModel response = new TableResponseModel();
    JSONArray jsonArray = jsonObject.getJSONArray(HEADINGS);
    JSONArray labelJsonArray = jsonObject.getJSONArray(LABEL_HEADINGS);
    for (int i = 0; i < labelJsonArray.length(); i++) {
      response.headings.add(labelJsonArray.getString(i));
    }

    List<Field> fields = new ArrayList<>(headersJson.length());
    for (int j = 0; j < headersJson.length(); j++) {
      fields.add(Report.class.getDeclaredField(headersJson.getString(j)));
    }
    JSONObject results = jsonObject.getJSONObject(TABLE);
    Map<String, List<List<ReportDataModel>>> tables = new HashMap<>(results.length());
    JSONArray dimensions = results.names();
    for (int i = 0; i < dimensions.length(); i++) {
      JSONArray period = results.getJSONArray(dimensions.getString(i));
      String key = getTableKeyByViewType(viewType, dimensions.getString(i));
      tables.put(key, new ArrayList<List<ReportDataModel>>(period.length()));
      List<Report> reports = new ArrayList<>();
      for (int j = 0; j < period.length(); j++) {
        JSONArray row = period.getJSONArray(j);
        Report r = constructReport(fields.subList(2, fields.size()), row);
        r.setTime(jsonArray.getString(j + 1));
        reports.add(r);
      }
      for (Report report : reports) {
        tables.get(key).add(getReportValues(report, ReportCompareField.NONE));
      }
    }
    response.table = tables;
    return response;
  }
  return null;
}
 
Example 20
Project: yacy_grid_mcp   File: Contract.java   View Source Code Vote up 4 votes
public Contract(JSONObject json) {
    this();
    if (json.has(Contract.KEY_METADATA)) this.put(KEY_METADATA, json.getJSONObject(KEY_METADATA));
    if (json.has(Contract.KEY_DATA)) this.setData(json.getJSONArray(KEY_DATA));
    if (json.has(KEY_ACTIONS)) this.put(KEY_ACTIONS, json.getJSONArray(KEY_ACTIONS));
}