Java Code Examples for com.eclipsesource.json.JsonValue#asArray()

The following examples show how to use com.eclipsesource.json.JsonValue#asArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZCashClientCaller.java    From zencash-swing-wallet-ui with MIT License 6 votes vote down vote up
private void decomposeJSONValue(String name, JsonValue val, Map<String, String> map)
{
	if (val.isObject())
	{
		JsonObject obj = val.asObject();
		for (String memberName : obj.names())
		{
			this.decomposeJSONValue(name + "." + memberName, obj.get(memberName), map);
		}
	} else if (val.isArray())
	{
		JsonArray arr = val.asArray();
		for (int i = 0; i < arr.size(); i++)
		{
			this.decomposeJSONValue(name + "[" + i + "]", arr.get(i), map);
		}
	} else
	{
		map.put(name, val.toString());
	}
}
 
Example 2
Source File: MetadataTemplate.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
void parseJSONMember(JsonObject.Member member) {
    JsonValue value = member.getValue();
    String memberName = member.getName();
    if (memberName.equals("type")) {
        this.type = value.asString();
    } else if (memberName.equals("key")) {
        this.key = value.asString();
    } else if (memberName.equals("displayName")) {
        this.displayName = value.asString();
    } else if (memberName.equals("hidden")) {
        this.isHidden = value.asBoolean();
    } else if (memberName.equals("description")) {
        this.description = value.asString();
    } else if (memberName.equals("options")) {
        this.options = new ArrayList<Option>();
        for (JsonValue option : value.asArray()) {
            this.options.add(new Option(option.asObject()));
        }
    } else if (memberName.equals("id")) {
        this.id = value.asString();
    }
}
 
Example 3
Source File: MetadataTemplate.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
void parseJSONMember(JsonObject.Member member) {
    JsonValue value = member.getValue();
    String memberName = member.getName();
    if (memberName.equals("templateKey")) {
        this.templateKey = value.asString();
    } else if (memberName.equals("scope")) {
        this.scope = value.asString();
    } else if (memberName.equals("displayName")) {
        this.displayName = value.asString();
    } else if (memberName.equals("hidden")) {
        this.isHidden = value.asBoolean();
    } else if (memberName.equals("fields")) {
        this.fields = new ArrayList<Field>();
        for (JsonValue field: value.asArray()) {
            this.fields.add(new Field(field.asObject()));
        }
    } else if (memberName.equals("id")) {
        this.id = value.asString();
    }
}
 
Example 4
Source File: FixedArrayJsonRule.java    From dungeon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void validate(JsonValue value) {
  super.validate(value);
  JsonArray array = value.asArray();
  if (rules.size() != array.size()) {
    throw new IllegalArgumentException("Array is not of the right size.");
  }
  for (int i = 0; i < rules.size(); i++) {
    rules.get(i).validate(array.values().get(i));
  }
}
 
Example 5
Source File: ArraySizeJsonRule.java    From dungeon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void validate(JsonValue value) {
  super.validate(value);
  JsonArray jsonArray = value.asArray();
  if (jsonArray.size() != arraySize) {
    throw new IllegalArgumentException(jsonArray + " size is not valid.");
  }
}
 
Example 6
Source File: JsonCreaturePresetFactory.java    From dungeon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static List<Drop> getDrops(JsonObject object) {
  if (object.get("drops") == null) {
    return Collections.emptyList();
  } else {
    List<Drop> list = new ArrayList<>();
    for (JsonValue value : object.get("drops").asArray()) {
      JsonArray dropArray = value.asArray();
      list.add(new Drop(new Id(dropArray.get(0).asString()), new Percentage(dropArray.get(1).asDouble())));
    }
    return list;
  }
}
 
Example 7
Source File: BlockJson.java    From Cubes with MIT License 5 votes vote down vote up
@Override
public ItemStackPlaceholder[] parse(JsonValue prop) {
  if (prop.isArray()) {
    JsonArray jsonArray = prop.asArray();
    ItemStackPlaceholder[] itemStacks = new ItemStackPlaceholder[jsonArray.size()];
    for (int i = 0; i < itemStacks.length; i++) {
      itemStacks[i] = parseSingle(jsonArray.get(i).asObject());
    }
    return itemStacks;
  } else {
    return new ItemStackPlaceholder[]{parseSingle(prop.asObject())};
  }
}
 
Example 8
Source File: ScopedToken.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
@Override
protected void parseJSONMember(JsonObject.Member member) {
    String memberName = member.getName();
    JsonValue value = member.getValue();
    if (memberName.equals("access_token")) {
        this.accessToken = value.asString();
    } else if (memberName.equals("token_type")) {
        this.tokenType = value.asString();
    } else if (memberName.equals("issued_token_type")) {
        this.issuedTokenType = value.asString();
    } else if (memberName.equals("restricted_to")) {
        this.restrictedTo = value.asArray();
    }
}
 
Example 9
Source File: BoxJsonObject.java    From box-android-sdk with Apache License 2.0 5 votes vote down vote up
public ArrayList<String> getAsStringArray(final String field){
    if (mInternalCache.get(field) != null){
        return (ArrayList<String>)mInternalCache.get(field);
    }
    JsonValue value = getAsJsonValue(field);
    if (value == null || value.isNull()) {
        return null;
    }
    ArrayList<String> strings = new ArrayList<String>(value.asArray().size());
    for (JsonValue member : value.asArray()){
        strings.add(member.asString());
    }
    mInternalCache.put(field, strings);
    return strings;
}
 
Example 10
Source File: BoxJsonObject.java    From box-android-sdk with Apache License 2.0 5 votes vote down vote up
public HashSet<String> getPropertyAsStringHashSet(String field) {
    if (mInternalCache.get(field) != null){
        return (HashSet<String>)mInternalCache.get(field);
    }
    JsonValue value = getAsJsonValue(field);
    if (value == null || value.isNull()) {
        return null;
    }
    HashSet<String> strings = new HashSet<String>(value.asArray().size());
    for (JsonValue member : value.asArray()){
        strings.add(member.asString());
    }
    mInternalCache.put(field, strings);
    return strings;
}
 
Example 11
Source File: BoxJsonObject.java    From box-android-sdk with Apache License 2.0 5 votes vote down vote up
public JsonArray getAsJsonArray(final String field){
    JsonValue value = getAsJsonValue(field);
    if (value == null || value.isNull()) {
        return null;
    }
    return value.asArray();
}
 
Example 12
Source File: Configurable.java    From Recaf with MIT License 5 votes vote down vote up
/**
 * @param field
 * 		Field accessor.
 * @param type
 * 		Field type.
 * @param value
 * 		Serialized representation.
 */
default void loadType(FieldWrapper field, Class<?> type, JsonValue value) {
	if (type.equals(ConfKeybinding.Binding.class)) {
		List<String> list = new ArrayList<>();
		JsonArray array = value.asArray();
		String name = field.key();
		array.forEach(v -> {
			if(v.isString())
				list.add(v.asString());
			else
				warn("Didn't properly load config for {}, expected all string arguments", name);
		});
		field.set(ConfKeybinding.Binding.from(list));
	}
}
 
Example 13
Source File: TleTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoad() {
	JsonObject tle = client.getTle();
	JsonValue data = tle.get("tle");
	assertNotNull(data);
	assertTrue(data.isArray());
	JsonArray dataArray = data.asArray();
	assertEquals(createTle(), findData("40069", dataArray));
}
 
Example 14
Source File: VariableArrayJsonRule.java    From dungeon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void validate(JsonValue value) {
  super.validate(value);
  JsonArray array = value.asArray();
  for (JsonValue arrayValue : array.values()) {
    rule.validate(arrayValue);
  }
}
 
Example 15
Source File: AndroidInjections.java    From CrossMobile with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void fromArray(JsonValue data, Collection<String> target) {
    if (data != null && data.isArray())
        for (JsonValue item : data.asArray())
            target.add(item.asString());
}
 
Example 16
Source File: BoxRetentionPolicyAssignment.java    From box-java-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
void parseJSONMember(JsonObject.Member member) {
    super.parseJSONMember(member);
    String memberName = member.getName();
    JsonValue value = member.getValue();
    try {
        if (memberName.equals("retention_policy")) {
            JsonObject policyJSON = value.asObject();
            if (this.retentionPolicy == null) {
                String policyID = policyJSON.get("id").asString();
                BoxRetentionPolicy policy = new BoxRetentionPolicy(getAPI(), policyID);
                this.retentionPolicy = policy.new Info(policyJSON);
            } else {
                this.retentionPolicy.update(policyJSON);
            }
        } else if (memberName.equals("assigned_to")) {
            JsonObject assignmentJSON = value.asObject();
            this.assignedToType = assignmentJSON.get("type").asString();
            if (this.assignedToType.equals(TYPE_ENTERPRISE)) {
                this.assignedToID = null;
            } else {
                this.assignedToID = assignmentJSON.get("id").asString();
            }
        } else if (memberName.equals("assigned_by")) {
            JsonObject userJSON = value.asObject();
            if (this.assignedBy == null) {
                String userID = userJSON.get("id").asString();
                BoxUser user = new BoxUser(getAPI(), userID);
                this.assignedBy = user.new Info(userJSON);
            } else {
                this.assignedBy.update(userJSON);
            }
        } else if (memberName.equals("assigned_at")) {
            this.assignedAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("filter_fields")) {
            JsonArray jsonFilters = value.asArray();
            List<MetadataFieldFilter> filterFields = new ArrayList<MetadataFieldFilter>();
            for (int i = 0; i < jsonFilters.size(); i++) {
                filterFields.add(new MetadataFieldFilter(jsonFilters.get(i).asObject()));
            }
            this.filterFields = filterFields;
        }
    } catch (Exception e) {
        throw new BoxDeserializationException(memberName, value.toString(), e);
    }
}
 
Example 17
Source File: JsonHelper.java    From typescript.java with MIT License 4 votes vote down vote up
public static JsonArray getArray(JsonObject obj, String name) {
	JsonValue value = obj.get(name);
	return value != null ? value.asArray() : null;
}
 
Example 18
Source File: Main.java    From jpexs-decompiler with GNU General Public License v3.0 4 votes vote down vote up
public static boolean checkForUpdates() {
    String currentVersion = ApplicationInfo.version;
    if (currentVersion.equals("unknown")) {
        // sometimes during development the version information is not available
        return false;
    }

    boolean showStable = Configuration.checkForUpdatesStable.get();
    boolean showNightly = Configuration.checkForUpdatesNightly.get();

    if (!showStable && !showNightly) {
        return false;
    }

    String currentTagName;
    if (ApplicationInfo.nightly) {
        currentTagName = "nightly" + ApplicationInfo.version_build;
    } else {
        currentTagName = "version" + ApplicationInfo.version_major + "." + ApplicationInfo.version_minor + "." + ApplicationInfo.version_release;
    }

    if (!showNightly) {
        //prereleases are not shown as latest, when checking latest nightly, this is useless
        JsonValue latestVersionInfoJson = urlGetJson(ApplicationInfo.GITHUB_RELEASES_LATEST_URL);
        if (latestVersionInfoJson == null) {
            return false;
        }
        String latestTagName = latestVersionInfoJson.asObject().get("tag_name").asString();
        if (currentTagName.equals(latestTagName)) {
            //no new version
            return false;
        }
    }

    JsonValue allChangesInfoJson = urlGetJson(ApplicationInfo.GITHUB_RELEASES_URL);
    if (allChangesInfoJson == null) {
        return false;
    }
    JsonArray arr = allChangesInfoJson.asArray();
    final java.util.List<Version> versions = new ArrayList<>();
    for (int i = 0; i < arr.size(); i++) {
        JsonObject versionObj = arr.get(i).asObject();
        String tagName = versionObj.get("tag_name").asString();
        if (currentVersion.equals(tagName)) {
            //Stop at current version, do not display more
            break;
        }
        Version v = new Version();
        v.versionName = versionObj.get("name").asString();
        //v.description = versionObj.get("body").asString();
        //Note: "body" is Markdown formatted and contains other things than changeslog, 
        //we cannot show it in FFDec correctly.
        v.description = "";
        v.releaseDate = versionObj.get("published_at").asString();
        boolean isNightly = versionObj.get("prerelease").asBoolean();
        if (isNightly && !showNightly) {
            continue;
        }

        if (!isNightly && !showStable) {
            continue;
        }

        versions.add(v);
    }

    if (!versions.isEmpty()) {
        View.execInEventDispatch(() -> {
            NewVersionDialog newVersionDialog = new NewVersionDialog(versions);
            newVersionDialog.setVisible(true);
            Configuration.lastUpdatesCheckDate.set(Calendar.getInstance());
        });

        return true;
    }

    Configuration.lastUpdatesCheckDate.set(Calendar.getInstance());
    return false;
}
 
Example 19
Source File: Configurable.java    From Recaf with MIT License 4 votes vote down vote up
/**
 * @param path
 * 		Path to json file of config.
 *
 * @throws IOException
 * 		When the file cannot be read.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
default void load(Path path) throws IOException {
	JsonObject json = Json.parse(FileUtils.readFileToString(path.toFile(), StandardCharsets.UTF_8)).asObject();
	for(FieldWrapper field : getConfigFields()) {
		String name = field.key();
		if(name == null)
			continue;
		final JsonValue value = json.get(name);
		if(value != null) {
			try {
				Class<?> type = field.type();
				if(type.equals(Boolean.TYPE))
					field.set(value.asBoolean());
				else if(type.equals(Integer.TYPE))
					field.set(value.asInt());
				else if(type.equals(Long.TYPE))
					field.set(value.asLong());
				else if(type.equals(Float.TYPE))
					field.set(value.asFloat());
				else if(type.equals(Double.TYPE))
					field.set(value.asDouble());
				else if(type.equals(String.class))
					field.set(value.asString());
				else if(type.isEnum())
					field.set(Enum.valueOf((Class<? extends Enum>) (Class<?>) field.type(), value.asString()));
				else if(type.equals(Resource.class)) {
					JsonObject object = value.asObject();
					String resPath = object.getString("path", null);
					if(object.getBoolean("internal", true))
						field.set(Resource.internal(resPath));
					else
						field.set(Resource.external(resPath));
				} else if(type.equals(List.class)) {
					List<Object> list = new ArrayList<>();
					JsonArray array = value.asArray();
					// We're gonna assume our lists just hold strings
					array.forEach(v -> {
						if(v.isString())
							list.add(v.asString());
						else
							warn("Didn't properly load config for {}, expected all string arguments", name);
					});
					field.set(list);
				} else if(supported(type))
					loadType(field, type, value);
				else
					warn("Didn't load config for {}, unsure how to serialize.", name);
			} catch(Exception ex) {
				error(ex, "Skipping bad option: {} - {}", path.getFileName(), name);
			}
		}
	}
	onLoad();
}
 
Example 20
Source File: JsonItemPresetFactory.java    From dungeon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Collection<ItemPreset> getItemPresets() {
  JsonObject objects = JsonObjectFactory.makeJsonObject(filename);
  Collection<ItemPreset> itemPresets = new ArrayList<>();
  for (JsonValue value : objects.get("items").asArray()) {
    JsonObject itemObject = value.asObject();
    ItemPreset preset = new ItemPreset();
    Id id = new Id(itemObject.get("id").asString());
    preset.setId(id);
    preset.setType(itemObject.get("type").asString());
    preset.setName(NameFactory.fromJsonObject(itemObject.get("name").asObject()));
    preset.setRarity(Rarity.valueOf(itemObject.get("rarity").asString()));
    preset.setTagSet(new TagSetParser<>(Item.Tag.class, itemObject.get("tags")).parse());
    if (itemObject.get("enchantments") != null) {
      for (JsonValue enchantment : itemObject.get("enchantments").asArray()) {
        Id enchantmentId = new Id(enchantment.asObject().get("id").asString());
        double probability = enchantment.asObject().get("probability").asDouble();
        preset.getEnchantmentRules().add(enchantmentId, probability);
      }
    }
    preset.setUnique(itemObject.getBoolean("unique", false));
    if (itemObject.get("decompositionPeriod") != null) {
      long seconds = DungeonTimeParser.parseDuration(itemObject.get("decompositionPeriod").asString()).getSeconds();
      preset.setPutrefactionPeriod(seconds);
    }
    JsonObject integrity = itemObject.get("integrity").asObject();
    preset.setIntegrity(new Integrity(integrity.get("current").asInt(), integrity.get("maximum").asInt()));
    preset.setVisibility(Percentage.fromString(itemObject.get("visibility").asString()));
    if (itemObject.get("luminosity") != null) {
      preset.setLuminosity(new Luminosity(Percentage.fromString(itemObject.get("luminosity").asString())));
    }
    preset.setWeight(Weight.newInstance(itemObject.get("weight").asDouble()));
    preset.setDamage(itemObject.get("damage").asInt());
    preset.setHitRate(Percentage.fromString(itemObject.get("hitRate").asString()));
    preset.setIntegrityDecrementOnHit(itemObject.get("integrityDecrementOnHit").asInt());
    if (itemObject.get("nutrition") != null) {
      preset.setNutrition(itemObject.get("nutrition").asInt());
    }
    if (itemObject.get("integrityDecrementOnEat") != null) {
      preset.setIntegrityDecrementOnEat(itemObject.get("integrityDecrementOnEat").asInt());
    }
    if (preset.getTagSet().hasTag(Tag.BOOK)) {
      preset.setText(itemObject.get("text").asString());
    }
    if (preset.getTagSet().hasTag(Tag.DRINKABLE)) {
      preset.setDrinkableDoses(itemObject.get("drinkableDoses").asInt());
      for (JsonValue effectValue : itemObject.get("drinkableEffects").asArray()) {
        JsonArray effectArray = effectValue.asArray();
        List<JsonValue> values = effectArray.values();
        Id effectId = new Id(values.get(0).asString());
        List<String> effectParameters = new ArrayList<>();
        for (int i = 1; i < values.size(); i++) {
          if (values.get(i).isString()) {
            // Calling toString() makes a JSON String, which includes the quotation marks.
            effectParameters.add(values.get(i).asString());
          } else {
            effectParameters.add(values.get(i).toString());
          }
        }
        preset.addDrinkableEffect(effectId, effectParameters);
      }
      preset.setIntegrityDecrementPerDose(itemObject.get("integrityDecrementPerDose").asInt());
    }
    if (itemObject.get("spell") != null) {
      preset.setSpellId(itemObject.get("spell").asString());
    }
    itemPresets.add(preset);
  }
  DungeonLogger.info("Loaded " + itemPresets.size() + " item presets.");
  return itemPresets;
}