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

The following are Jave code examples for showing how to use add() 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: DRM-Desktop   File: Message.java   View Source Code Vote up 6 votes
public JsonObject toJson(){
    JsonObject obj = new JsonObject();
    JsonObject message = new JsonObject();
    message.addProperty("action", action);

    JsonArray pr = new JsonArray();
    for (String key : params.keySet()) {
        pr.add(params.get(key).toJson());
    }
    message.add("params", pr);

    obj.add("message", message);

    if(this.destination != null) {
        obj.addProperty("destination", this.destination);
    }

    obj.addProperty("id", this.id.toString());

    return obj;
}
 
Example 2
Project: DecompiledMinecraft   File: ServerStatusResponse.java   View Source Code Vote up 6 votes
public JsonElement serialize(ServerStatusResponse.PlayerCountData p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
    JsonObject jsonobject = new JsonObject();
    jsonobject.addProperty("max", (Number)Integer.valueOf(p_serialize_1_.getMaxPlayers()));
    jsonobject.addProperty("online", (Number)Integer.valueOf(p_serialize_1_.getOnlinePlayerCount()));

    if (p_serialize_1_.getPlayers() != null && p_serialize_1_.getPlayers().length > 0)
    {
        JsonArray jsonarray = new JsonArray();

        for (int i = 0; i < p_serialize_1_.getPlayers().length; ++i)
        {
            JsonObject jsonobject1 = new JsonObject();
            UUID uuid = p_serialize_1_.getPlayers()[i].getId();
            jsonobject1.addProperty("id", uuid == null ? "" : uuid.toString());
            jsonobject1.addProperty("name", p_serialize_1_.getPlayers()[i].getName());
            jsonarray.add(jsonobject1);
        }

        jsonobject.add("sample", jsonarray);
    }

    return jsonobject;
}
 
Example 3
Project: bStats-Metrics   File: Metrics.java   View Source Code Vote up 6 votes
/**
 * Gets the plugin specific data.
 * This method is called using Reflection.
 *
 * @return The plugin specific data.
 */
public JsonObject getPluginData() {
    JsonObject data = new JsonObject();

    String pluginName = plugin.getName();
    String pluginVersion = plugin.getVersion().orElse("unknown");

    data.addProperty("pluginName", pluginName);
    data.addProperty("pluginVersion", pluginVersion);

    JsonArray customCharts = new JsonArray();
    for (CustomChart customChart : charts) {
        // Add the data of the custom charts
        JsonObject chart = customChart.getRequestJsonObject(logger, logFailedRequests);
        if (chart == null) { // If the chart is null, we skip it
            continue;
        }
        customCharts.add(chart);
    }
    data.add("customCharts", customCharts);

    return data;
}
 
Example 4
Project: webauthndemo   File: PublicKeyCredentialDescriptor.java   View Source Code Vote up 6 votes
/**
 * @return Encoded JsonObject representation of PublicKeyCredentialDescriptor
 */
public JsonObject getJsonObject() {
  JsonObject result = new JsonObject();
  result.addProperty("type", type.toString());

  result.addProperty("id", BaseEncoding.base64().encode(id));
  JsonArray transports = new JsonArray();
  if (this.transports != null) {
    for (AuthenticatorTransport t : this.transports) {
      JsonPrimitive element = new JsonPrimitive(t.toString());
      transports.add(element);
    }
    if (transports.size() > 0) {
      result.add("transports", transports);
    }
  }

  return result;
}
 
Example 5
Project: modName   File: BiomeSettings.java   View Source Code Vote up 6 votes
protected static <T extends GroupedBiomeEntry> void writeGroupedEntryMap(JsonObject o, LinkedHashMap<String, T> list) {
    for (T biome : list.values()) {
        String catname = biome.category.toString();
        if (!o.has(catname)) {
            o.add(catname, new JsonObject());
        }
        JsonObject catobject = JsonUtil.getAsObject(o, catname);

        if (!catobject.has(biome.group)) {
            catobject.add(biome.group, new JsonArray());
        }
        JsonArray groupobject = JsonUtil.getAsArray(catobject, biome.group);

        groupobject.add(biome.toJson());
    }
}
 
Example 6
Project: bStats-Metrics   File: Metrics.java   View Source Code Vote up 5 votes
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, int[]> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean allSkipped = true;
    for (Map.Entry<String, int[]> entry : map.entrySet()) {
        if (entry.getValue().length == 0) {
            continue; // Skip this invalid
        }
        allSkipped = false;
        JsonArray categoryValues = new JsonArray();
        for (int categoryValue : entry.getValue()) {
            categoryValues.add(new JsonPrimitive(categoryValue));
        }
        values.add(entry.getKey(), categoryValues);
    }
    if (allSkipped) {
        // Null = skip the chart
        return null;
    }
    data.add("values", values);
    return data;
}
 
Example 7
Project: TruenoNPC   File: TruenoNPC_v1_11_r1.java   View Source Code Vote up 5 votes
private void cacheSkin(SkinData skindata){
    JsonObject jsonFile = getChacheFile(plugin);
    JsonArray newskindata = new JsonArray();
    if(jsonFile!=null){
        JsonArray oldskindata = jsonFile.getAsJsonArray("skindata");
        Iterator it = oldskindata.iterator();
        while(it.hasNext()){
            JsonElement element = (JsonElement) it.next();
            if(element.getAsJsonObject().get("id").getAsInt()==this.npcid){
                // element.getAsJsonObject().remove("value");
                //element.getAsJsonObject().remove("signature");
                //element.getAsJsonObject().addProperty("value", skindata.getValue());
                //element.getAsJsonObject().addProperty("signature", skindata.getSignature());
            }else {
                newskindata.add(element);
            }
        }
    }
    JsonObject skin = new JsonObject();
    skin.addProperty("id", this.npcid);
    skin.addProperty("value", skindata.getValue());
    skin.addProperty("signature", skindata.getSignature());
    newskindata.add(skin);

    JsonObject obj = new JsonObject();
    obj.add("skindata", newskindata);
    try {
        plugin.getDataFolder().mkdir();
        File file = new File(plugin.getDataFolder().getPath()+"/truenonpcdata.json");
        file.createNewFile();
        FileWriter writer = new FileWriter(file);
        writer.write(obj.toString());
        writer.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: raven   File: ServiceHelper.java   View Source Code Vote up 5 votes
public static JsonArray fromSet(Set<String> sets) {
    JsonArray array = new JsonArray();
    if (null != sets && sets.size() > 0) {
        for (String item : sets) {
            array.add(new JsonPrimitive(item));
        }
    }
    return array;
}
 
Example 9
Project: graphflow   File: Subgraphs.java   View Source Code Vote up 5 votes
@Override
public JsonObject toJson() {

    JsonObject vertexMap = new JsonObject();
    for (String variable : variableIndices.keySet()) {
        vertexMap.addProperty(variable, variableIndices.get(variable));
    }

    JsonObject vertexData = new JsonObject();
    for (int vertexId : vertices.keySet()) {
        vertexData.add(String.valueOf(vertexId), vertices.get(vertexId).toJson());
    }

    JsonObject edgeData = new JsonObject();
    for (long edgeId : edges.keySet()) {
        edgeData.add(String.valueOf(edgeId), edges.get(edgeId).toJson());
    }

    JsonArray subgraphsResult = new JsonArray();
    for (Subgraph subgraph : subgraphs) {
        subgraphsResult.add(subgraph.toJson());
    }

    JsonObject result = new JsonObject();
    result.addProperty(JsonKeyConstants.RESPONSE_TYPE.toString(),
        ResultType.SUBGRAPHS.toString());
    result.add(JsonKeyConstants.VERTEX_MAP.toString(), vertexMap);
    result.add(JsonKeyConstants.VERTICES.toString(), vertexData);
    result.add(JsonKeyConstants.EDGES.toString(), edgeData);
    result.add(JsonKeyConstants.SUBGRAPHS.toString(), subgraphsResult);
    addExecutionTimeToJson(result);
    return result;
}
 
Example 10
Project: newblog   File: JMXClient.java   View Source Code Vote up 5 votes
public JsonArray getMemoryPoolDetail() {
    List<MemoryPoolMXBean> mps = ManagementFactory.getMemoryPoolMXBeans();
    JsonArray array = new JsonArray();
    for (MemoryPoolMXBean mp : mps) {
        if (mp.getName().contains("Eden") || mp.getName().contains("Survivor")  //win与linux上的不同,顾使用contains
                || mp.getName().contains("Tenured") || mp.getName().contains("Old")) {
            array.add(getMpJsonObject(mp));
        }
    }
    return array;
}
 
Example 11
Project: SkinFixer   File: SkinConfig.java   View Source Code Vote up 5 votes
public JsonElement toJson(String uuid, String username, String skinUrl, String capeUrl) {
    // Lets add all the information in case the game really needs them

    JsonObject tex = new JsonObject();

    if(skinUrl != null && !skinUrl.isEmpty()) {
        JsonObject skin = new JsonObject();
        skin.addProperty("url", skinUrl);
        tex.add("SKIN", skin);
    }

    if(capeUrl != null && !capeUrl.isEmpty()) {
        JsonObject cape = new JsonObject();
        cape.addProperty("url", capeUrl);
        tex.add("CAPE", cape);
    }

    JsonObject textures = new JsonObject();
    textures.addProperty("timestamp", (int)(System.currentTimeMillis() / 1000L));
    textures.addProperty("profileId", uuid);
    textures.addProperty("profileName", username);
    textures.add("textures", tex);

    JsonObject property = new JsonObject();
    property.addProperty("name", "textures");
    property.addProperty("value", DatatypeConverter.printBase64Binary(textures.toString().getBytes()));

    JsonArray properties = new JsonArray();
    properties.add(property);

    JsonObject obj = new JsonObject();
    obj.addProperty("id", uuid);
    obj.addProperty("name", username);
    obj.add("properties", properties);

    return obj;
}
 
Example 12
Project: Cypher   File: ApiMock.java   View Source Code Vote up 5 votes
private JsonObject getNewAccountData() {
	JsonObject data = new JsonObject();
	JsonArray events = new JsonArray();

	JsonObject event = new JsonObject();
	JsonObject settings = new JsonObject();
	settings.addProperty("shouldBeTrue", false);

	event.addProperty("type", "ex.example.test");
	event.add("content", settings);
	events.add(event);

	data.add("events", events);
	return data;
}
 
Example 13
Project: CustomWorldGen   File: FMLNetworkHandler.java   View Source Code Vote up 5 votes
public static void enhanceStatusQuery(JsonObject jsonobject)
{
    JsonObject fmlData = new JsonObject();
    fmlData.addProperty("type", "FML");
    JsonArray modList = new JsonArray();
    for (ModContainer mc : Loader.instance().getActiveModList())
    {
        JsonObject modData = new JsonObject();
        modData.addProperty("modid", mc.getModId());
        modData.addProperty("version", mc.getVersion());
        modList.add(modData);
    }
    fmlData.add("modList", modList);
    jsonobject.add("modinfo", fmlData);
}
 
Example 14
Project: kjsonpatch   File: TestDataGenerator.java   View Source Code Vote up 5 votes
private static JsonArray getArrayNode(List<String> args) {
    JsonArray countryNode = new JsonArray();
    for(String arg : args){
        countryNode.add(arg);
    }
    return countryNode;
}
 
Example 15
Project: CoreX   File: TimingData.java   View Source Code Vote up 5 votes
JsonArray export() {
    JsonArray json = JsonUtil.toArray(this.id, this.count, this.totalTime);
    if (this.lagCount > 0) {
        json.add(this.lagCount);
        json.add(this.lagTotalTime);
    }
    return json;
}
 
Example 16
Project: ForgeHax   File: PlayerInfo.java   View Source Code Vote up 5 votes
public PlayerInfo(String name) {
    JsonArray ar = new JsonArray();
    ar.add(name);

    UUID _id = UUID.randomUUID();
    List<Name> _temp = Collections.emptyList();
    boolean _offline = true;

    try {
        JsonArray array = getResources(new URL("https://api.mojang.com/profiles/minecraft"), "POST", ar).getAsJsonArray();
        JsonObject node = array.get(0).getAsJsonObject();

        UUID uuid = PlayerInfoHelper.getIdFromString(node.get("id").getAsString());
        Objects.requireNonNull(uuid);

        _id = uuid;
        _temp = ImmutableList.copyOf(getHistoryOfNames(_id));
        _offline = false;
    } catch (Throwable t) {
        _id = EntityPlayerSP.getOfflineUUID(name);
        _temp = Collections.singletonList(new Name(name));
        _offline = true;
    } finally {
        this.id = _id;
        this.names = _temp;
        this.offlineId = EntityPlayerSP.getOfflineUUID(getName());
        this.isOfflinePlayer = _offline;
    }
}
 
Example 17
Project: ProjectAres   File: ConfigUtils.java   View Source Code Vote up 5 votes
public static JsonArray toJson(List list) {
    JsonArray json = new JsonArray();
    for(Object item : list) {
        json.add(toJson(item));
    }
    return json;
}
 
Example 18
Project: text   File: GsonComponentSerializer.java   View Source Code Vote up 5 votes
@Override
public JsonElement serialize(final Component component, final Type type, final JsonSerializationContext context) {
  final JsonObject object = new JsonObject();
  if(component instanceof TextComponent) {
    object.addProperty("text", ((TextComponent) component).content());
  } else if(component instanceof TranslatableComponent) {
    final TranslatableComponent tc = (TranslatableComponent) component;
    object.addProperty("translate", tc.key());
    if(!tc.args().isEmpty()) {
      final JsonArray with = new JsonArray();
      for(final Component arg : tc.args()) {
        with.add(this.serialize(arg, arg.getClass(), context));
      }
      object.add("with", with);
    }
  } else if(component instanceof ScoreComponent) {
    final ScoreComponent sc = (ScoreComponent) component;
    final JsonObject score = new JsonObject();
    score.addProperty("name", sc.name());
    score.addProperty("objective", sc.objective());
    // score component value is optional
    if(sc.value() != null) score.addProperty("value", sc.value());
    object.add("score", score);
  } else if(component instanceof SelectorComponent) {
    object.addProperty("selector", ((SelectorComponent) component).pattern());
  } else if(component instanceof KeybindComponent) {
    object.addProperty("keybind", ((KeybindComponent) component).keybind());
  } else {
    throw new IllegalArgumentException("Don't know how to serialize " + component + " as a Component");
  }

  if(!component.children().isEmpty()) {
    final JsonArray extra = new JsonArray();
    for(final Component child : component.children()) {
      extra.add(this.serialize(child, child.getClass(), context));
    }
    object.add("extra", extra);
  }

  if(component.hasStyling()) {
    for(final TextDecoration decoration : TextDecoration.values()) {
      final TextDecoration.State flag = component.decoration(decoration);
      if(flag != TextDecoration.State.NOT_SET) object.addProperty(decoration.toString(), flag == TextDecoration.State.TRUE);
    }
    if(component.color() != null) object.add("color", context.serialize(component.color()));
    if(component.insertion() != null) object.add("insertion", context.serialize(component.insertion()));
    @Nullable final ClickEvent clickEvent = component.clickEvent();
    if(clickEvent != null) {
      final JsonObject clickEventO = new JsonObject();
      clickEventO.add("action", context.serialize(clickEvent.action()));
      clickEventO.addProperty("value", clickEvent.value());
      object.add("clickEvent", clickEventO);
    }
    @Nullable final HoverEvent hoverEvent = component.hoverEvent();
    if(hoverEvent != null) {
      final JsonObject hoverEventO = new JsonObject();
      hoverEventO.add("action", context.serialize(hoverEvent.action()));
      hoverEventO.add("value", this.serialize(hoverEvent.value(), type, context));
      object.add("hoverEvent", hoverEventO);
    }
  }

  return object;
}
 
Example 19
Project: CoreX   File: TimingsHistory.java   View Source Code Vote up 4 votes
TimingsHistory() {
    this.endTime = System.currentTimeMillis() / 1000;
    this.startTime = TimingsManager.historyStart / 1000;

    if (timedTicks % 1200 != 0 || MINUTE_REPORTS.isEmpty()) {
        this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size() + 1]);
        this.minuteReports[this.minuteReports.length - 1] = new MinuteReport();
    } else {
        this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size()]);
    }

    long ticks = 0;
    for (MinuteReport mr : this.minuteReports) {
        ticks += mr.ticksRecord.timed;
    }

    this.totalTicks = ticks;
    this.totalTime = fullServerTickTimer.record.totalTime;
    this.entries = new TimingsHistoryEntry[TimingsManager.TIMINGS.size()];

    int i = 0;
    for (Timing timing : TimingsManager.TIMINGS) {
        this.entries[i++] = new TimingsHistoryEntry(timing);
    }

    final Map<Integer, AtomicInteger> entityCounts = new HashMap<>();
    final Map<Integer, AtomicInteger> blockEntityCounts = new HashMap<>();
    final Gson GSON = new Gson();
    // Information about all loaded entities/block entities
    for (Level level : Server.getInstance().getLevels().values()) {
        JsonArray jsonLevel = new JsonArray();
        for (BaseFullChunk chunk : level.getChunks().values()) {
            entityCounts.clear();
            blockEntityCounts.clear();

            //count entities
            for (Entity entity : chunk.getEntities().values()) {
                if (!entityCounts.containsKey(entity.getNetworkId()))
                    entityCounts.put(entity.getNetworkId(), new AtomicInteger(0));
                entityCounts.get(entity.getNetworkId()).incrementAndGet();
                entityMap.put(entity.getNetworkId(), entity.getClass().getSimpleName());
            }

            //count block entities
            for (BlockEntity blockEntity : chunk.getBlockEntities().values()) {
                if (!blockEntityCounts.containsKey(blockEntity.getBlock().getId()))
                    blockEntityCounts.put(blockEntity.getBlock().getId(), new AtomicInteger(0));
                blockEntityCounts.get(blockEntity.getBlock().getId()).incrementAndGet();
                blockEntityMap.put(blockEntity.getBlock().getId(), blockEntity.getClass().getSimpleName());
            }

            if (blockEntityCounts.isEmpty() && entityCounts.isEmpty()) {
                continue;
            }

            JsonArray jsonChunk = new JsonArray();
            jsonChunk.add(chunk.getX());
            jsonChunk.add(chunk.getZ());
            jsonChunk.add(GSON.toJsonTree(JsonUtil.mapToObject(entityCounts.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue().get()))).getAsJsonObject());
            jsonChunk.add(GSON.toJsonTree(JsonUtil.mapToObject(blockEntityCounts.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue().get()))).getAsJsonObject());
            jsonLevel.add(jsonChunk);
        }

        if (!levelMap.containsKey(level.getName())) levelMap.put(level.getName(), levelIdPool++);
        levels.add(String.valueOf(levelMap.get(level.getName())), jsonLevel);
    }
}
 
Example 20
Project: SpaceGame   File: Level.java   View Source Code Vote up 4 votes
@Override
public JsonElement serialize(Level src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject obj = new JsonObject();
    
    obj.add("commands", context.serialize(src.commands, new TypeToken<HashMap<String, Command>>() {}.getType()));
    obj.add("entities", context.serialize(src.entities, new TypeToken<HashMap<String, EntityPrototype>>() {}.getType()));
    
    JsonArray state = new JsonArray();
    
    for (Entity entity : src.getECS().getEntities()) {
        state.add(context.serialize(entity));
    }
    
    obj.add("state", state);
    
    JsonObject events = new JsonObject();
    
    for (Entry<Class<? extends Event>, LuaEventHandler> eventHandler : src.events.entrySet()) {
        events.addProperty(eventHandler.getKey().getName(), eventHandler.getValue().getOriginal());
    }
    
    obj.add("events", events);
    
    return obj;
}