Example usage for com.google.gson JsonArray JsonArray

List of usage examples for com.google.gson JsonArray JsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonArray JsonArray.

Prototype

public JsonArray() 

Source Link

Document

Creates an empty JsonArray.

Usage

From source file:beans.cart.SimpleCart.java

@Override
public String toStringJsonArray() {

    JsonArray jsonarr = new JsonArray();

    JsonObject job;//from   w  w  w .  jav  a  2  s .c  om
    for (Item item : items) {
        job = new JsonObject();
        job.addProperty("item", item.toStringJson());
        jsonarr.add(job);
    }

    return jsonarr.toString();
}

From source file:beans.TripleStoreBean.java

public static String answerLiteqQuery(String query, boolean useCache) {
    JsonObject response = new JsonObject();
    Gson gson = new Gson();

    if (useCache) {
        String cachedResult = CacheBean.getCachedLiteqQueryResult(query.hashCode());
        if (cachedResult != null) {
            Logger.getLogger(TripleStoreBean.class.getName()).log(Level.INFO, "returning cached result");
            return cachedResult;
        }/*from  w w w  . j  a va  2  s. c o  m*/
    }
    JsonElement result = null;
    JsonArray values;

    ResultSet rs;
    Connection conn = null;
    try {
        conn = getTripleStoreConnection();
        Statement stmt = conn.createStatement();

        boolean more = stmt.execute(query);
        ResultSetMetaData data = stmt.getResultSet().getMetaData();

        if (data.getColumnCount() == 1) {
            result = new JsonArray();
        } else {
            result = new JsonObject();
        }

        while (more) {
            rs = stmt.getResultSet();
            while (rs.next()) {
                if (data.getColumnCount() > 1) {
                    String key = convertToIRI(rs.getObject(1));
                    if (key == null) {
                        key = rs.getString(1);
                    }
                    String value = convertToIRI(rs.getObject(2));
                    if (value == null) {
                        value = rs.getString(2);
                    }
                    if (((JsonObject) result).has(key)) {
                        values = ((JsonObject) result).get(key).getAsJsonArray();
                        values.add(new JsonPrimitive(value));
                    } else {
                        values = new JsonArray();
                        values.add(new JsonPrimitive(value));
                        ((JsonObject) result).add(key, values);
                    }
                } else if (data.getColumnCount() == 1) {
                    String key = convertToIRI(rs.getObject(1));
                    if (key == null) {
                        key = rs.getString(1);
                    }
                    ((JsonArray) result).add(new JsonPrimitive(key));
                }
            }
            more = stmt.getMoreResults();
        }
        response.add("response", result);

        if (useCache) {
            CacheBean.storeResponseInCache(gson.toJson(response), query.hashCode());
        }
    } catch (SQLException ex) {
        Logger.getLogger(TripleStoreBean.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(TripleStoreBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return gson.toJson(response);
}

From source file:bind.JsonTreeWriter.java

License:Apache License

@Override
public JsonWriter beginArray() throws IOException {
    JsonArray array = new JsonArray();
    put(array);//from ww  w .  j av  a  2  s  .  c  o m
    stack.add(array);
    return this;
}

From source file:bisq.desktop.main.dao.governance.result.VoteResultView.java

License:Open Source License

private JsonElement getVotingHistoryJson() {
    JsonArray cyclesArray = new JsonArray();

    sortedCycleListItemList.sorted(Comparator.comparing(CycleListItem::getCycleStartTime))
            .forEach(cycleListItem -> {
                JsonObject cycleJson = new JsonObject();
                // No domain data, taken from UI model
                // TODO move the data structure needed for UI to core and use as pure domain model and use that here
                cycleJson.addProperty("cycleIndex", cycleListItem.getCycleIndex());
                cycleJson.addProperty("cycleDateTime", cycleListItem.getCycleDateTime(false));
                cycleJson.addProperty("votesCount", cycleListItem.getNumVotesAsString());
                cycleJson.addProperty("voteWeight", cycleListItem.getMeritAndStake());
                cycleJson.addProperty("issuance", cycleListItem.getIssuance());
                cycleJson.addProperty("startTime", cycleListItem.getCycleStartTime());
                cycleJson.addProperty("totalAcceptedVotes",
                        cycleListItem.getResultsOfCycle().getNumAcceptedVotes());
                cycleJson.addProperty("totalRejectedVotes",
                        cycleListItem.getResultsOfCycle().getNumRejectedVotes());

                JsonArray proposalsArray = new JsonArray();
                List<EvaluatedProposal> evaluatedProposals = cycleListItem.getResultsOfCycle()
                        .getEvaluatedProposals();
                evaluatedProposals.sort(Comparator.comparingLong(o -> o.getProposal().getCreationDate()));

                evaluatedProposals.forEach(evaluatedProp -> {
                    JsonObject proposalJson = new JsonObject();
                    proposalJson.addProperty("isAccepted",
                            evaluatedProp.isAccepted() ? "Accepted" : "Rejected");

                    // Proposal
                    Proposal proposal = evaluatedProp.getProposal();
                    proposalJson.addProperty("proposal.name", proposal.getName());
                    proposalJson.addProperty("proposal.link", proposal.getLink());
                    proposalJson.addProperty("proposal.version", proposal.getVersion());
                    proposalJson.addProperty("proposal.creationDate", proposal.getCreationDate());
                    proposalJson.addProperty("proposal.txId", proposal.getTxId());
                    proposalJson.addProperty("proposal.txType", proposal.getTxType().name());
                    proposalJson.addProperty("proposal.quorumParam", proposal.getQuorumParam().name());
                    proposalJson.addProperty("proposal.thresholdParam", proposal.getThresholdParam().name());
                    proposalJson.addProperty("proposal.proposalType", proposal.getType().name());

                    if (proposal.getExtraDataMap() != null)
                        proposalJson.addProperty("proposal.extraDataMap",
                                proposal.getExtraDataMap().toString());

                    switch (proposal.getType()) {
                    case UNDEFINED:
                        break;
                    case COMPENSATION_REQUEST:
                        CompensationProposal compensationProposal = (CompensationProposal) proposal;
                        proposalJson.addProperty("proposal.requestedBsq",
                                compensationProposal.getRequestedBsq().getValue());
                        proposalJson.addProperty("proposal.bsqAddress", compensationProposal.getBsqAddress());
                        break;
                    case REIMBURSEMENT_REQUEST:
                        ReimbursementProposal reimbursementProposal = (ReimbursementProposal) proposal;
                        proposalJson.addProperty("proposal.requestedBsq",
                                reimbursementProposal.getRequestedBsq().getValue());
                        proposalJson.addProperty("proposal.bsqAddress", reimbursementProposal.getBsqAddress());
                        break;
                    case CHANGE_PARAM:
                        ChangeParamProposal changeParamProposal = (ChangeParamProposal) proposal;
                        Param param = changeParamProposal.getParam();
                        proposalJson.addProperty("proposal.param", param.name());
                        proposalJson.addProperty("proposal.param.defaultValue", param.getDefaultValue());
                        proposalJson.addProperty("proposal.param.type", param.getParamType().name());
                        proposalJson.addProperty("proposal.param.maxDecrease", param.getMaxDecrease());
                        proposalJson.addProperty("proposal.param.maxIncrease", param.getMaxIncrease());
                        proposalJson.addProperty("proposal.paramValue", changeParamProposal.getParamValue());
                        break;
                    case BONDED_ROLE:
                        RoleProposal roleProposal = (RoleProposal) proposal;
                        Role role = roleProposal.getRole();
                        proposalJson.addProperty("proposal.requiredBondUnit",
                                roleProposal.getRequiredBondUnit());
                        proposalJson.addProperty("proposal.unlockTime", roleProposal.getUnlockTime());
                        proposalJson.addProperty("proposal.role.uid", role.getUid());
                        proposalJson.addProperty("proposal.role.name", role.getName());
                        proposalJson.addProperty("proposal.role.link", role.getLink());
                        BondedRoleType bondedRoleType = role.getBondedRoleType();
                        proposalJson.addProperty("proposal.bondedRoleType", bondedRoleType.name());
                        // bondedRoleType enum must not change anyway so we don't print it
                        break;
                    case CONFISCATE_BOND:
                        ConfiscateBondProposal confiscateBondProposal = (ConfiscateBondProposal) proposal;
                        proposalJson.addProperty("proposal.lockupTxId", confiscateBondProposal.getLockupTxId());
                        break;
                    case GENERIC:
                        // No extra fields
                        break;
                    case REMOVE_ASSET:
                        RemoveAssetProposal removeAssetProposal = (RemoveAssetProposal) proposal;
                        proposalJson.addProperty("proposal.tickerSymbol",
                                removeAssetProposal.getTickerSymbol());
                        break;
                    }/*from  w  ww .  j a  v  a 2s. c o m*/

                    ProposalVoteResult proposalVoteResult = evaluatedProp.getProposalVoteResult();
                    proposalJson.addProperty("stakeOfAcceptedVotes",
                            proposalVoteResult.getStakeOfAcceptedVotes());
                    proposalJson.addProperty("stakeOfRejectedVotes",
                            proposalVoteResult.getStakeOfRejectedVotes());
                    proposalJson.addProperty("numAcceptedVotes", proposalVoteResult.getNumAcceptedVotes());
                    proposalJson.addProperty("numRejectedVotes", proposalVoteResult.getNumRejectedVotes());
                    proposalJson.addProperty("numIgnoredVotes", proposalVoteResult.getNumIgnoredVotes());
                    proposalJson.addProperty("numActiveVotes", proposalVoteResult.getNumActiveVotes());
                    proposalJson.addProperty("quorum", proposalVoteResult.getQuorum());
                    proposalJson.addProperty("threshold", proposalVoteResult.getThreshold());

                    // Not part of pure domain data, but useful to add here
                    // required quorum and threshold for cycle for proposal type
                    proposalJson.addProperty("requiredQuorum",
                            proposalService.getRequiredQuorum(proposal).value);
                    proposalJson.addProperty("requiredThreshold",
                            proposalService.getRequiredThreshold(proposal));

                    // TODO provide better domain object as now we loop inside the loop. Use lookup map instead....
                    JsonArray votesArray = new JsonArray();
                    evaluatedProposals.stream()
                            .filter(evaluatedProposal -> evaluatedProposal.getProposal().equals(proposal))
                            .forEach(evaluatedProposal -> {
                                List<DecryptedBallotsWithMerits> decryptedVotesForCycle = cycleListItem
                                        .getResultsOfCycle().getDecryptedVotesForCycle();
                                // Make sure the votes are sorted so we can easier compare json files from different users
                                decryptedVotesForCycle.sort(
                                        Comparator.comparing(DecryptedBallotsWithMerits::getBlindVoteTxId));
                                decryptedVotesForCycle.forEach(decryptedBallotsWithMerits -> {
                                    JsonObject voteJson = new JsonObject();
                                    // Domain data of decryptedBallotsWithMerits
                                    voteJson.addProperty("hashOfBlindVoteList", Utilities.bytesAsHexString(
                                            decryptedBallotsWithMerits.getHashOfBlindVoteList()));
                                    voteJson.addProperty("blindVoteTxId",
                                            decryptedBallotsWithMerits.getBlindVoteTxId());
                                    voteJson.addProperty("voteRevealTxId",
                                            decryptedBallotsWithMerits.getVoteRevealTxId());
                                    voteJson.addProperty("stake", decryptedBallotsWithMerits.getStake());

                                    voteJson.addProperty("voteWeight",
                                            decryptedBallotsWithMerits.getMerit(daoStateService));
                                    String voteResult = decryptedBallotsWithMerits
                                            .getVote(evaluatedProp.getProposalTxId())
                                            .map(vote -> vote.isAccepted() ? "Accepted" : "Rejected")
                                            .orElse("Ignored");
                                    voteJson.addProperty("vote", voteResult);
                                    votesArray.add(voteJson);
                                });
                            });

                    proposalJson.addProperty("numberOfVotes", votesArray.size());
                    proposalJson.add("votes", votesArray);

                    proposalsArray.add(proposalJson);
                });
                cycleJson.addProperty("numberOfProposals", proposalsArray.size());
                cycleJson.add("proposals", proposalsArray);
                cyclesArray.add(cycleJson);
            });
    return cyclesArray;
}

From source file:blockplus.exports.ContextRepresentation.java

License:Open Source License

public JsonElement encodeBoard() {
    final JsonObject boardState = new JsonObject();
    final JsonObject meta = new JsonObject();
    final JsonObject data = new JsonObject();
    final Board board = this.context.board();
    final int rows = board.rows();
    final int columns = board.columns();
    meta.addProperty("rows", rows);
    meta.addProperty("columns", columns);
    final Set<Colors> colors = board.getColors();
    for (final Colors color : colors) {
        final JsonArray jsonArray = new JsonArray();
        for (final IPosition position : board.getSelves(color))
            jsonArray.add(new JsonPrimitive(columns * position.row() + position.column() % rows)); // TODO extract method
        data.add(color.toString(), jsonArray);
    }//from   w ww . java  2s .  c  o m
    boardState.add("dimension", meta);
    boardState.add("cells", data);
    return boardState;
}

From source file:blockplus.exports.PiecesRepresentation.java

License:Open Source License

private static String _toJson() {
    final JsonArray pieces = new JsonArray();
    for (final Polyomino polyomino : Polyomino.set()) {
        final Iterable<IPosition> positions = polyomino.positions();
        if (positions.iterator().hasNext()) {
            final JsonArray data = new JsonArray();
            for (final IPosition position : positions) {
                final JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("y", position.row());
                jsonObject.addProperty("x", position.column());
                data.add(jsonObject);/*www.ja v a2s  . co  m*/
            }
            pieces.add(data);
        }
    }
    return pieces.toString();
}

From source file:blockplus.transport.VirtualClient.java

License:Open Source License

@Override
public void onMessage(final String message) {
    final JsonParser jsonParser = new JsonParser();
    final JsonObject jsonObject = jsonParser.parse(message).getAsJsonObject();
    final String type = jsonObject.get("type").getAsString();
    if (type.equals("game")) {
        final JsonObject data = jsonObject.get("data").getAsJsonObject();
        final int k = data.get("players").getAsInt();
        this.color = Colors.values()[k - 1].toString();
    }//from  w w  w . j  a  va 2  s .c  o m
    if (type.equals("update")) {
        final JsonObject data = jsonObject.get("data").getAsJsonObject();

        //            System.out.println(data);

        final String color = data.get("color").getAsString();
        if (color.equals(this.color)) {
            if (data.get("isTerminal").getAsBoolean()) {
                System.out.println("Game Over");
            } else {

                final Colors side = Colors.valueOf(this.color);

                final BoardEncoding boardEncoding = new BoardEncoding();
                final Board board = boardEncoding.decode(data.get("board").getAsJsonObject());

                //                    final OptionsEncoding optionsEncoding = new OptionsEncoding();
                //                    final Options options = optionsEncoding.decode(data.get("options").getAsJsonObject());

                final SidesEncoding sidesEncoding = new SidesEncoding();
                final Sides sides = sidesEncoding.decode(data.get("pieces").getAsJsonObject());

                final Context context = new Context(side, sides, board);
                final AI3 ai = new AI3();

                //                    final IPosition position = this.testAI(side, board, options);
                //                    final Set<IPosition> positions = this.moveSupplier(options, position);

                System.out.println();
                System.out.println(side);
                final Set<IPosition> positions = ai.get(context);

                final JsonArray jsonArray = new JsonArray();
                for (final IPosition iPosition : positions)
                    jsonArray.add(new JsonPrimitive(20 * iPosition.row() + iPosition.column() % 20)); // TODO !!!

                final MoveSubmit moveSubmit = new MoveSubmit(jsonArray);

                try {
                    this.send(moveSubmit);
                } catch (final Exception e) {
                }
            }
        }
    }
}

From source file:br.com.anteros.social.facebook.utils.JsonUtils.java

License:Apache License

public static <T> T fromJson(String json, Class<T> cls) {
    Gson gson = buildGson();/*from  w  w w  . ja  v  a 2 s  .c o  m*/

    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(json);

    if (cls != null && cls.isArray() && element instanceof JsonArray == false) {
        JsonArray jsonArray = new JsonArray();
        jsonArray.add(element);

        Type listType = new TypeToken<T>() {
        }.getType();
        return gson.fromJson(jsonArray, listType);
    }

    return gson.fromJson(json, cls);
}

From source file:br.com.anteros.social.facebook.utils.JsonUtils.java

License:Apache License

public static <T> T fromJsonExcludeFields(String json, Class<T> cls) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(json);

    if (cls.isArray() && element instanceof JsonArray == false) {
        JsonArray jsonArray = new JsonArray();
        jsonArray.add(element);/*  www. j  a  v  a 2 s. c o m*/

        Type listType = new TypeToken<T>() {
        }.getType();
        return gson.fromJson(jsonArray, listType);
    }

    return gson.fromJson(json, cls);
}

From source file:br.com.thiaguten.contrib.JsonContrib.java

License:Apache License

/**
 * Appends key and/or value to json//from  ww  w  .  ja v  a2s.c o  m
 *
 * @param json  string json which will be modified
 * @param key   key that will be appended
 * @param value value that will be appended
 * @return the specified JSON string with appended key and/or value
 */
public static String appendValueToJson(String json, String key, Object value) {
    JsonElement jsonElement = parseObject(json);

    if (jsonElement != null) {
        if (jsonElement.isJsonPrimitive()) {
            JsonArray jsonArray = new JsonArray();
            jsonArray.add(jsonElement);
            jsonArray.add(objectToJsonElementTree(value));
            return jsonArray.toString();
        } else if (jsonElement.isJsonObject()) {
            if (key == null) {
                throw new IllegalArgumentException(
                        "to append some value into a JsonObject the 'key' parameter must not be null");
            }
            JsonObject jsonObject = (JsonObject) jsonElement;
            jsonObject.add(key, objectToJsonElementTree(value));
            return jsonObject.toString();
        } else if (jsonElement.isJsonArray()) {
            JsonArray jsonArray = (JsonArray) jsonElement;
            jsonArray.add(objectToJsonElementTree(value));
            return jsonArray.toString();
        }
    }
    return getJsonElementAsString(jsonElement);
}