Java Code Examples for com.google.gson.JsonArray.forEach()

The following are Jave code examples for showing how to use forEach() of the com.google.gson.JsonArray 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: MineIDE   File: DataManager.java   View Source Code Vote up 6 votes
@Override
public void fromJson(final JsonElement json)
{
    if (!json.isJsonArray())
        throw new IllegalArgumentException("json is not an array");
    final JsonArray array = json.getAsJsonArray();

    array.forEach((dt) ->
    {
        if (dt.isJsonObject())
        {
            final JsonObject dtObj = dt.getAsJsonObject();
            final String key = dtObj.get("key").getAsString();
            final String type = dtObj.get("type").getAsString();
            final DataType<?> dataType = DataManager.typesValues.get(type);
            if (dataType != null)
            {
                final Object value = dataType.fromJson(dtObj.get("value"));
                this.setOrAddInternalValue(dataType, key, value);
            }
        }
    });
}
 
Example 2
Project: thjson   File: JSONtoTHJSONConverter.java   View Source Code Vote up 6 votes
private void writeMap(String key, JsonObject json) {
	if (json.has("class")) {
		String clazz = json.get("class").getAsString();
		if ("array".equals(clazz)) {
			String type = json.get("type").getAsString();
			JsonArray elements = json.get("elements").getAsJsonArray();
			writer.beginList(key, type);
			elements.forEach(this::writeValue);
			writer.endList();
		} else {
			writer.beginObject(key, clazz);
			json.entrySet().forEach(e -> {
				if (!e.getKey().equals("class")) {
					writeProperty(e.getKey(), e.getValue());
				}
			});
			writer.endObject();
		}
	} else {
		writer.beginMap(key);
		json.entrySet().forEach(e -> writeProperty(e.getKey(), e.getValue()));
		writer.endMap();
	}
}
 
Example 3
Project: SpaceGame   File: ControllableComponent.java   View Source Code Vote up 6 votes
@Override
public ControllableComponent deserialize(JsonElement json, Type typeOfT,
                                         JsonDeserializationContext context) throws JsonParseException {
    JsonArray arr = json.getAsJsonArray();
    
    ControllableComponent control = new ControllableComponent();
    
    Level level = Level.deserializing();
    
    arr.forEach((element) -> {
        String str = element.getAsString();
        if (level.getCommands().containsKey(str)) {
            control.commands.add(level.getCommands().get(str));
        } else {
            throw new JsonParseException("Could not find command " + str);
        }
    });
    
    return control;
}
 
Example 4
Project: arquillian-reporter   File: ReportJsonDeserializer.java   View Source Code Vote up 6 votes
private Report setDefaultValues(Report report, JsonObject jsonReport) {
    JsonElement name = jsonReport.get("name");
    JsonArray entries = jsonReport.get("entries").getAsJsonArray();
    JsonArray subReports = jsonReport.get("subReports").getAsJsonArray();

    report.setName(prepareGsonParser().fromJson(name, StringKey.class));


    entries.forEach(subEntry -> {
        Entry entry = prepareGsonParser().fromJson(subEntry, Entry.class);
        report.getEntries().add(entry);
    });

    subReports.forEach(subReport -> {
        Report subReportEntry = prepareGsonParser().fromJson(subReport, Report.class);
        report.getSubReports().add(subReportEntry);
    });

    return report;
}
 
Example 5
Project: synthea_java   File: HealthRecord.java   View Source Code Vote up 5 votes
public static List<Code> fromJson(JsonArray jsonCodes) {
  List<Code> codes = new ArrayList<>();
  jsonCodes.forEach(item -> {
    codes.add(new Code((JsonObject) item));
  });
  return codes;
}
 
Example 6
Project: MineIDE   File: Translation.java   View Source Code Vote up 5 votes
@Override
protected void dataFromJson(final JsonElement data)
{
    if (!data.isJsonArray())
        throw new IllegalArgumentException("json is not an array");
    final JsonArray array = data.getAsJsonArray();

    array.forEach((trans) ->
    {
        if (trans.isJsonObject())
        {
            final JsonObject transObj = trans.getAsJsonObject();
            final String key = transObj.get("key").getAsString();
            this.addKey(key);
            final JsonArray translations = transObj.get("translations").getAsJsonArray();

            translations.forEach((elem) ->
            {
                if (elem.isJsonObject())
                {
                    final JsonObject elemObj = elem.getAsJsonObject();
                    final String lang = elemObj.get("lang").getAsString();
                    this.addLanguage(lang);
                    this.setTranslation(key, lang, elemObj.get("value").getAsString());
                }
            });
        }
    });
}
 
Example 7
Project: SurvivalAPI   File: SpawnEggsModule.java   View Source Code Vote up 5 votes
@Override
public Map<String, Object> buildFromJson(Map<String, JsonElement> configuration) throws Exception
{
    if (configuration.containsKey("entities"))
    {
        JsonArray entityTypesJson = configuration.get("entities").getAsJsonArray();
        entityTypesJson.forEach(element -> this.addEntityType(EntityType.valueOf(element.getAsString().toUpperCase())));
    }

    return this.build();
}
 
Example 8
Project: SurvivalAPI   File: DropMyEffectsModule.java   View Source Code Vote up 5 votes
@Override
public Map<String, Object> buildFromJson(Map<String, JsonElement> configuration) throws Exception
{
    if (configuration.containsKey("blacklist"))
    {
        JsonArray blacklistJson = configuration.get("blacklist").getAsJsonArray();
        blacklistJson.forEach(jsonElement -> this.blacklistPotionEffect(PotionEffectType.getByName(jsonElement.getAsString())));
    }

    return this.build();
}
 
Example 9
Project: SurvivalAPI   File: PainfulStonesModule.java   View Source Code Vote up 5 votes
@Override
public Map<String, Object> buildFromJson(Map<String, JsonElement> configuration) throws Exception
{
    if (configuration.containsKey("blocks"))
    {
        JsonArray blocksJson = configuration.get("blocks").getAsJsonArray();
        blocksJson.forEach(element -> this.blocks.add(Material.matchMaterial(element.getAsString())));
    }

    if (configuration.containsKey("damages"))
        this.setDamages(configuration.get("damages").getAsDouble());

    return this.build();
}
 
Example 10
Project: EMC   File: MarketplaceAPI.java   View Source Code Vote up 5 votes
/**
 * Retrieves a list with the names of all mods licensed to the user
 *
 * @return {@code String array} of the mod names
 */
public static List<String> getLicensedModNames() {
	JsonObject json = new Gson().fromJson(getSafe(getUserLicensedProductNamesURL()), JsonObject.class);
	JsonArray arr = json.get("data").getAsJsonArray();
	List<String> list = new ArrayList<String>();
	arr.forEach((jsonElement) -> list.add(jsonElement.getAsString()));
	return list;
}
 
Example 11
Project: arquillian-reporter   File: ReportJsonDeserializer.java   View Source Code Vote up 5 votes
private Report parseExecutionReport(JsonObject jsonReport, JsonDeserializationContext context){
    ExecutionReport executionReport = new ExecutionReport();

    JsonArray testSuiteReportsJson = jsonReport.get("testSuiteReports").getAsJsonArray();
    testSuiteReportsJson.forEach(suite -> {
        Report testSuiteReport = prepareGsonParser().fromJson(suite, TestSuiteReport.class);
        executionReport.getTestSuiteReports().add((TestSuiteReport) testSuiteReport);
    });

    return setDefaultValues(executionReport, jsonReport);
}
 
Example 12
Project: arquillian-reporter   File: ReportJsonDeserializer.java   View Source Code Vote up 5 votes
private Report parseTestSuiteReport(JsonObject jsonReport){
    TestSuiteReport testSuiteReport = new TestSuiteReport();

    JsonArray testClassReportsJson = jsonReport.get("testClassReports").getAsJsonArray();
    testClassReportsJson.forEach(testClass -> {
        Report testClassReport = prepareGsonParser().fromJson(testClass, TestClassReport.class);
        testSuiteReport.getTestClassReports().add((TestClassReport) testClassReport);
    });

    setConfiguration(testSuiteReport, jsonReport);
    setStartAndStop(testSuiteReport, jsonReport);
    return setDefaultValues(testSuiteReport, jsonReport);
}
 
Example 13
Project: arquillian-reporter   File: ReportJsonDeserializer.java   View Source Code Vote up 5 votes
private Report parseTestClassReport(JsonObject jsonReport){
    TestClassReport testClassReport = new TestClassReport();

    JsonArray testMethodReportsJson = jsonReport.get("testMethodReports").getAsJsonArray();
    testMethodReportsJson.forEach(testMethod -> {
        Report testMethodReport = prepareGsonParser().fromJson(testMethod, TestMethodReport.class);
        testClassReport.getTestMethodReports().add((TestMethodReport) testMethodReport);
    });

    setConfiguration(testClassReport, jsonReport);
    setStartAndStop(testClassReport, jsonReport);
    return setDefaultValues(testClassReport, jsonReport);
}
 
Example 14
Project: matrix-java-sdk   File: MatrixJson.java   View Source Code Vote up 4 votes
private static void encodeCanonicalArray(JsonArray array, JsonWriterUnchecked writer) throws IOException {
    writer.beginArray();
    array.forEach(el -> encodeCanonicalElement(el, writer));
    writer.endArray();
}
 
Example 15
Project: shuffleboard   File: LayoutSaver.java   View Source Code Vote up 4 votes
@Override
public Layout deserialize(JsonElement json, JsonDeserializationContext context) throws JsonParseException {
  JsonObject obj = json.getAsJsonObject();
  String name = obj.get("_type").getAsString();
  JsonArray children = obj.get("_children").getAsJsonArray();

  Layout layout = Components.getDefault().createComponent(name).flatMap(TypeUtils.optionalCast(Layout.class))
      .orElseThrow(() -> new JsonParseException("Can't find layout name " + name));

  if (layout instanceof Sourced) {
    Sourced sourcedLayout = (Sourced) layout;
    for (int i = 0; i > Integer.MIN_VALUE; i++) {
      String prop = "_source" + i;
      if (obj.has(prop)) {
        String uri = obj.get(prop).getAsString();
        Optional<? extends DataSource<?>> source = Sources.getDefault().get(uri);
        try {
          if (source.isPresent()) {
            sourcedLayout.addSource(source.get());
          } else {
            sourcedRestorer.addDestroyedSourcesForAllDataTypes(sourcedLayout, uri);
          }
        } catch (IncompatibleSourceException e) {
          Logger.getLogger(getClass().getName()).log(Level.WARNING, "Couldn't load source", e);
          sourcedRestorer.addDestroyedSourcesForAllDataTypes(sourcedLayout, uri);
        }
      } else {
        break;
      }
    }
  }

  JsonElement title = obj.get("_title");
  if (title != null) {
    layout.setTitle(title.getAsString());
  }

  children.forEach(child -> {
    String childName = child.getAsJsonObject().get("_type").getAsString();
    Optional<Type> childType = Components.getDefault().javaTypeFor(childName);
    childType.map(t -> context.deserialize(child, t))
        .flatMap(TypeUtils.optionalCast(Component.class))
        .ifPresent(layout::addChild);
  });

  return layout;
}
 
Example 16
Project: thjson   File: JSONtoTHJSONConverter.java   View Source Code Vote up 4 votes
private void writeArray(String key, JsonArray array) {
	writer.beginArray(key);
	array.forEach(this::writeValue);
	writer.endArray();
}
 
Example 17
Project: OpenRPG   File: OpenPlayerData.java   View Source Code Vote up 3 votes
@Override
public OpenPlayerData jsonDeserialize(File file) throws FileNotFoundException {
    JsonObject object = GSON.fromJson(new FileReader(file), JsonObject.class);

    this.uuid = UUID.fromString(file.getName().replaceFirst("[.][^.]+$", ""));
    this.level = object.get("level").getAsInt();
    this.exp = object.get("exp").getAsInt();
    this.region = RegionManager.getInstance().getRegion(object.get("region").getAsInt());
    this.name = object.get("name").getAsString();

    JsonArray array = object.get("unlocked_regions").getAsJsonArray();

    array.forEach(element -> this.regions.add(RegionManager.getInstance().getRegion(element.getAsInt())));

    array = object.get("quests").getAsJsonArray();

    array.forEach(element -> this.quests.add(QuestManager.getInstance().getQuest(element.getAsInt())));

    array = object.get("completedQuests").getAsJsonArray();

    array.forEach(element -> this.completedQuests.add(QuestManager.getInstance().getQuest(element.getAsInt())));

    array = object.get("cooldownQuests").getAsJsonArray();

    array.forEach(element -> {
        JsonObject jsonObject = element.getAsJsonObject();

        this.cooldownQuests.put(QuestManager.getInstance().getQuest(jsonObject.get("id").getAsInt()), jsonObject.get("cooldown").getAsInt());
    });

    return this;
}
 
Example 18
Project: DiscordDevRant   File: Util.java   View Source Code Vote up 2 votes
/**
 * Create a list from a JSON array.
 *
 * @param json      The JSON array to convert to a list.
 * @param converter The converter for converting individual JSON elements.
 * @param <T>       The type to convert the elements to.
 * @return A list of elements converted from the JSON.
 */
static <T> List<T> jsonToList(JsonArray json, Function<JsonElement, T> converter) {
    List<T> result = new ArrayList<>(json.size());
    json.forEach(j -> result.add(converter.apply(j)));
    return result;
}