下面列出了android.content.pm.PackageStats#org.json.JSONArray 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
Trigger fromJSON(String data) {
try {
JSONObject d = new JSONObject(data);
connectorType = Type.valueOf(JsonHelper.safeGetString(d, "connectorType"));
JSONArray array = d.getJSONArray("triggerList");
list.clear();
for (int i = 0; i < array.length(); i++) {
Trigger newItem = instantiate(new JSONObject(array.getString(i)));
add(newItem);
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
return this;
}
@Override
public byte[] asByteArray() {
try {
JSONArray array = object.getJSONArray(name);
if (array != null) {
byte[] bytes = new byte[array.length()];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) array.getInt(i);
}
return bytes;
}
} catch (JSONException e) {
String value = asString();
if (value != null) {
return value.getBytes();
}
}
return null;
}
/**
* Retrieves stored notification channels.
*
* @param context The application context.
* @return List of stored channels or null.
*/
private static List<HashMap<String, Object>> retrieveNotificationChannels(Context context) {
if (context == null) {
return null;
}
try {
SharedPreferences preferences = context.getSharedPreferences(Constants.Defaults.LEANPLUM,
Context.MODE_PRIVATE);
String jsonChannels = preferences.getString(Constants.Defaults.NOTIFICATION_CHANNELS_KEY,
null);
if (jsonChannels == null) {
return null;
}
JSONArray json = new JSONArray(jsonChannels);
return JsonConverter.listFromJson(json);
} catch (Exception e) {
Log.e("Failed to convert notification channels json.");
}
return null;
}
@Override
protected Void doInBackground(Void... voids) {
try {
if (!parseFailed) {
after = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.AFTER_KEY);
JSONArray children = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
for (int i = 0; i < children.length(); i++) {
userDataArrayList.add(parseUserDataBase(children.getJSONObject(i)));
}
}
} catch (JSONException e) {
parseFailed = true;
e.printStackTrace();
}
return null;
}
public List<GraphObject> deserializeArray(JSONArray data)
{
List<GraphObject> list = new ArrayList<GraphObject>();
if (data != null)
{
int n = data.length();
for (int i = 0; i < n; i++)
{
try
{
list.add(deserializeObject(data.getJSONObject(i)));
}
catch (JSONException e)
{}
}
}
return list;
}
@Test(groups = {"wso2.greg", "wso2.greg.es"}, description = "PromoteLifeCycle with fault user",
dependsOnMethods = {"testPrepareForTestRun"})
public void CheckLCHistory() throws LogViewerLogViewerException, RemoteException,
JSONException {
ClientResponse response = getLifeCycleHistory(assetId, "restservice", lifeCycleName);
Assert.assertTrue(response.getStatusCode() == 200, "Fault user accepted");
JSONObject historyObj = new JSONObject(response.getEntity(String.class));
JSONArray dataObj = historyObj.getJSONArray("data");
Assert.assertEquals(((JSONObject) ((JSONObject) dataObj.get(0)).getJSONArray("action").
get(0)).getString("name"), "Demote");
Assert.assertEquals(((JSONObject) ((JSONObject) dataObj.get(1)).getJSONArray("action").
get(0)).getString("name"), "Demote");
Assert.assertEquals(((JSONObject) ((JSONObject) dataObj.get(2)).getJSONArray("action").
get(0)).getString("name"), "Promote");
Assert.assertEquals(((JSONObject) ((JSONObject) dataObj.get(3)).getJSONArray("action").
get(0)).getString("name"), "Promote");
Assert.assertEquals(dataObj.length(), 8);
}
/**
* JSONの中に入っているuriを変換する.
* <p>
* <p>
* 変換するuriはcontent://から始まるuriのみ変換する。<br/>
* それ以外のuriは何も処理しない。
* </p>
*
* @param settings DeviceConnect設定
* @param root 変換するJSONObject
* @throws JSONException JSONの解析に失敗した場合
*/
private static void convertUri(final DConnectSettings settings, final JSONObject root) throws JSONException {
@SuppressWarnings("unchecked") // Using legacy API
Iterator<String> it = root.keys();
while (it.hasNext()) {
String key = it.next();
Object value = root.opt(key);
if (value instanceof String) {
if (isUriKey(key) && startWithContent((String) value)) {
String u = createUri(settings, (String) value);
root.put(key, u);
}
} else if (value instanceof JSONObject) {
convertUri(settings, (JSONObject) value);
} else if (value instanceof JSONArray) {
JSONArray array = (JSONArray) value;
int length = array.length();
for (int i = 0; i < length; i++) {
JSONObject json = array.optJSONObject(i);
if (json != null) {
convertUri(settings, json);
}
}
}
}
}
private void parseItems(List<GalleryItem> items, JSONObject jsonBody)
throws IOException, JSONException {
JSONObject photosJsonObject = jsonBody.getJSONObject("photos");
JSONArray photoJsonArray = photosJsonObject.getJSONArray("photo");
for (int i = 0; i < photoJsonArray.length(); i++) {
JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);
GalleryItem item = new GalleryItem();
item.setId(photoJsonObject.getString("id"));
item.setCaption(photoJsonObject.getString("title"));
if (!photoJsonObject.has("url_s")) {
continue;
}
item.setUrl(photoJsonObject.getString("url_s"));
item.setOwner(photoJsonObject.getString("owner"));
items.add(item);
}
}
/**
* Reads the double value from the Json Array for specified index
*
* @param jsonArray The {@link JSONArray} to read the index from
* @param index The key to read
* @param required Whether the index is required. If <code>true</code>,
* attempting to read it when it is <code>null</code> will throw
* a {@link JSONException}
* @param notNull Whether the value is allowed to be <code>null</code>. If
* <code>true</code>, will throw a {@link JSONException} if the
* value is null
* @return The read value
* @throws JSONException If the double was unable to be read, or if the
* required/notNull flags were violated
*/
public static double readDouble(final JSONArray jsonArray, final int index,
final boolean required, final boolean notNull)
throws JSONException {
if (required) {
//Will throw JsonException if mapping doesn't exist
return jsonArray.getDouble(index);
}
if (notNull && jsonArray.isNull(index)) {
//throw JsonException because key is null
throw new JSONException(String.format(Locale.US, NULL_VALUE_FORMAT_ARRAY, index));
}
double value = 0.0;
if (!jsonArray.isNull(index)) {
value = jsonArray.getDouble(index);
}
return value;
}
public PercentileMetric(METRIC_TYPE type, Object val)
{
this.type = type;
try
{
JSONArray jsonArray = (JSONArray) val;
Map<String,Number> percentiles = new HashMap<>(jsonArray.length()/2);
for (int i = 0, length = jsonArray.length(); i < length; i++)
{
percentiles.put(jsonArray.getString(i++),jsonArray.getDouble(i));
}
value.put(type.toString(), percentiles);
}
catch (ClassCastException cce)
{
logger.debug("ClassCastException for "+val);
}
catch (JSONException e)
{
logger.debug("Failed to process percentile for "+val+ " "+e.getMessage());
}
}
public boolean isAtMeMsg(EMMessage message){
EaseUser user = EaseUserUtils.getUserInfo(message.getFrom());
if(user != null){
try {
JSONArray jsonArray = message.getJSONArrayAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG);
for(int i = 0; i < jsonArray.length(); i++){
String username = jsonArray.getString(i);
if(username.equals(EMClient.getInstance().getCurrentUser())){
return true;
}
}
} catch (Exception e) {
//perhaps is a @ all message
String atUsername = message.getStringAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG, null);
if(atUsername != null){
if(atUsername.toUpperCase().equals(EaseConstant.MESSAGE_ATTR_VALUE_AT_MSG_ALL)){
return true;
}
}
return false;
}
}
return false;
}
public static String addContextInfo(String str, HttpServletRequest request) {
try {
JSONArray inArr = new JSONArray(str);
JSONArray addedArr = new JSONArray();
for (int i = 0; i < inArr.length(); i++)
addedArr.put(inArr.get(i));
addedArr.put(getContainerInfo(request.getSession().getServletContext()).getJson());
addedArr.put(getRequestInfo(request).getJson());
addedArr.put(getSessionInfo(request.getSession()).getJson());
return addedArr.toString(2);
}
catch (Exception ex) {
LoggerUtil.getStandardLogger().error(ex.getMessage(), ex);
return str;
}
}
static Map<String, Object> convertJSONObjectToHashMap(JSONObject jsonObject) {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONArray keys = jsonObject.names();
for (int i = 0; i < keys.length(); ++i) {
String key;
try {
key = keys.getString(i);
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
value = convertJSONObjectToHashMap((JSONObject) value);
}
map.put(key, value);
} catch (JSONException e) {
}
}
return map;
}
private int countTestUsers() {
TestSession session = getTestSessionWithSharedUser(null);
String appAccessToken = TestSession.getAppAccessToken();
assertNotNull(appAccessToken);
String applicationId = session.getApplicationId();
assertNotNull(applicationId);
String fqlQuery = String.format("SELECT id FROM test_account WHERE app_id = %s", applicationId);
Bundle parameters = new Bundle();
parameters.putString("q", fqlQuery);
parameters.putString("access_token", appAccessToken);
Request request = new Request(null, "fql", parameters, null);
Response response = request.executeAndWait();
JSONArray data = (JSONArray) response.getGraphObject().getProperty("data");
return data.length();
}
CalEventInnerData(@NonNull String data, @NonNull PluginDataFormat format, int version) throws IllegalStorageDataException {
switch (format) {
default:
try {
JSONObject jsonObject = new JSONObject(data);
this.conditions = new ArraySet<>();
JSONArray jsonArray_conditions = jsonObject.optJSONArray(T_condition);
for (int i = 0; i < jsonArray_conditions.length(); i++) {
String condition = jsonArray_conditions.getString(i);
for (int j = 0; j < condition_name.length; j++) {
this.conditions.add(condition);
}
}
} catch (JSONException e) {
throw new IllegalStorageDataException(e);
}
}
}
private void removeSelfDependencies(JSONObject pDiagram)
{
JSONArray edges = pDiagram.getJSONArray("edges");
List<JSONObject> newEdges = new ArrayList<>();
for( int i = 0; i < edges.length(); i++ )
{
JSONObject object = edges.getJSONObject(i);
if( object.getString("type").equals("DependencyEdge") && object.getInt("start") == object.getInt("end") )
{
aMigrated = true; // We don't add the dependency, essentially removing it.
}
else
{
newEdges.add(object);
}
}
pDiagram.put("edges", new JSONArray(newEdges));
}
/**
* 将联系人信息列表转成json字符串
* @param phoneInfoList
* @return
*/
private String wrapPhoneInfoToContactStr(List<PhoneInfo> phoneInfoList){
if(phoneInfoList == null || phoneInfoList.size() == 0){
return "";
}
JSONArray jsonArray = new JSONArray();
for(PhoneInfo phoneInfo: phoneInfoList){
try {
JSONObject member = new JSONObject();
member.put(KEY_PHONE_NUM,phoneInfo.getPhoneNum());
member.put(KEY_CONTACT_VERSION,phoneInfo.getVersion());
jsonArray.put(member);
} catch (JSONException e) {
e.printStackTrace();
}
}
String result = jsonArray.toString();
byte[] bytes = result.getBytes();
Log.d(TAG, "wrapPhoneInfoToContactStr: bytes.length ="+bytes.length);
return jsonArray.toString();
}
private JSONArray convertListToJsonArray(Object value)
throws InvocationTargetException, IllegalAccessException {
JSONArray array = new JSONArray();
List<Object> list = (List<Object>) value;
for(Object obj : list) {
// Send null, if this is an array of arrays we are screwed
array.put(obj != null ? getJsonValue(obj, obj.getClass(), null /* field */) : null);
}
return array;
}
public static CharSequence formatJson(String json) {
try {
json = json.trim();
if (json.startsWith("[")) {
JSONArray jsonArray = new JSONArray(json);
return jsonArray.toString(4);
} else {
JSONObject jsonObject = new JSONObject(json);
return jsonObject.toString(4);
}
} catch (Exception e) {
Logger.e("non json content", e);
return json;
}
}
private void addProjections(IDataSet dataSet, JSONArray categories, Map<String, String> columnAliasToName, ArrayList<AbstractSelectionField> projections)
throws JSONException {
for (int i = 0; i < categories.length(); i++) {
JSONObject category = categories.getJSONObject(i);
addProjection(dataSet, projections, category, columnAliasToName);
}
}
/**
* Gives all possible genres for a given channel based on it's json contents.
*
* @param json the json parsed as a String.
* @return the array of all the genres for the channel.
*/
public static String[] getGenresArrayFromJson(String json) {
try {
JSONArray jsonArray = new JSONArray(json);
String[] genresArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
genresArray[i] = jsonArray.getString(i);
}
return (genresArray);
} catch (JSONException js) {
js.printStackTrace();
}
return (null);
}
@Test
@Description("A request for assigning a target multiple times results in a Bad Request when multiassignment is disabled.")
public void multiassignmentRequestNotAllowedIfDisabled() throws Exception {
final String targetId = testdataFactory.createTarget().getControllerId();
final Long dsId = testdataFactory.createDistributionSet().getId();
final JSONArray body = new JSONArray();
body.put(getAssignmentObject(targetId, MgmtActionType.SOFT));
body.put(getAssignmentObject(targetId, MgmtActionType.FORCED));
mvc.perform(post("/rest/v1/distributionsets/{ds}/assignedTargets", dsId).content(body.toString())
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
}
public String askForNotificationPermission(JSONArray args){
this.log("askForNotificationPermission", args);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = "Default Name";
String channelDescription = "Default Description";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
NotificationChannel channel = new NotificationChannel(CountlyPush.CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(channelDescription);
notificationManager.createNotificationChannel(channel);
}
}
CountlyPush.init(activity.getApplication(), pushTokenTypeVariable);
FirebaseApp.initializeApp(context);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("Tag", "getInstanceId failed", task.getException());
return;
}
String token = task.getResult().getToken();
CountlyPush.onTokenRefresh(token);
}
});
return "askForNotificationPermission";
}
public static String getTagValue(JSONObject json, String tag) throws JSONException {
JSONObject jsonTag = json.getJSONObject(tag);
JSONArray valueArray = jsonTag.getJSONArray("Value");
if (valueArray.length() != 1) {
throw new JSONException(
"Expected single value for tag: "
+ tag
+ " in JSON:\n"
+ valueArray.toString());
}
return valueArray.getString(0);
}
public boolean torrentRemove(List<Long> ids) {
boolean ret = true;
JSONObject params = new JSONObject();
try {
params.put("method", "torrent-remove");
JSONObject args = new JSONObject();
args.put("ids", new JSONArray(ids));
args.put("delete-local-data", false);
log.debug(args.toString());
params.put("arguments", args);
TransmissionVO vo = execute(params);
if (vo != null) {
if (!StringUtils.equals(vo.getResult(), "success")) {
ret = false;
}
}
} catch (JSONException e) {
log.error(e.getMessage());
}
return ret;
}
/**
* Parse a edge's schema definition.
*/
private void parseSchemaEdge(JSONObject obj) {
this.table_name_ = obj.getString("Name");
String from_vertex_type = obj.getString("FromVertexTypeName");
String to_vertex_type = obj.getString("ToVertexTypeName");
/**
* Spark will raise exception when found duplicate column names,
* but TigerGraph edges' source vertex and target vertex can be of the same type.
* So prefix was added here.
*/
if (from_vertex_type.equals(to_vertex_type) && this.isGettingEdge_) {
this.attribute_list_.add(new Attribute("from." + from_vertex_type, "STRING", Boolean.TRUE));
this.attribute_list_.add(new Attribute("to." + to_vertex_type, "STRING", Boolean.TRUE));
} else {
this.attribute_list_.add(new Attribute(from_vertex_type, "STRING", Boolean.TRUE));
this.attribute_list_.add(new Attribute(to_vertex_type, "STRING", Boolean.TRUE));
}
JSONArray attributes = obj.getJSONArray("Attributes");
for(int i = 0; i < attributes.length(); i++){
String attr_name = attributes.getJSONObject(i).getString("AttributeName");
Object value = attributes.getJSONObject(i).get("AttributeType");
String attr_type = "";
if (value instanceof JSONObject) {
attr_type = ((JSONObject)value).getString("Name");
this.attribute_list_.add(new Attribute(attr_name, attr_type, Boolean.FALSE));
}
}
}
@Test
public void testTagFromLogAll() throws Exception {
createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
IPath[] clonePaths = createTestProjects(workspaceLocation);
for (IPath clonePath : clonePaths) {
// clone a repo
JSONObject clone = clone(clonePath);
String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
String cloneCommitUri = clone.getString(GitConstants.KEY_COMMIT);
// get project/folder metadata
WebRequest request = getGetRequest(cloneContentLocation);
WebResponse response = webConversation.getResponse(request);
assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
JSONObject folder = new JSONObject(response.getText());
JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
String folderTagUri = gitSection.getString(GitConstants.KEY_TAG);
// get the full log
JSONArray commits = log(cloneCommitUri);
assertEquals(1, commits.length());
String commitLocation = commits.getJSONObject(0).getString(ProtocolConstants.KEY_LOCATION);
// tag
tag(commitLocation, "tag1");
// check
JSONArray tags = listTags(folderTagUri);
assertEquals(1, tags.length());
assertEquals("tag1", tags.getJSONObject(0).get(ProtocolConstants.KEY_NAME));
}
}
@Override
public List<VolumeMO> listVolumes(String filterKey, String filterValue) throws Exception {
List<VolumeMO> volumes = new ArrayList<>();
JSONArray jsonArray = client.listVolumes(filterKey, filterValue);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject volume = jsonArray.getJSONObject(i);
volumes.add(VolumeMOBuilder.build(volume));
}
logger.info(String.format("OceanStor Volume List for %S=%s : %s", filterKey, filterValue ,volumes));
return volumes;
}
private void removeFromFavorites(String itemName) {
favorites.remove(itemName);
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
JSONArray jsArray = new JSONArray(favorites);
prefs.edit().putString("favorites", jsArray.toString()).apply();
favorites = getFavorites();
generateList();
}
private void addGarbageFilePathList(ArrayList<String> list, DataEntity de) throws JSONException {
JSONArray array = de.getJSONArray(RubbishConst.key_Encrypted_Path_JSONArray);
int len = array.length();
for (int i = 0; i < len; i++) {
list.add(array.get(i).toString());
}
}