List of usage examples for com.google.gson JsonArray add
public void add(JsonElement element)
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); }//w w w . j a v a2 s. c om 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(); }/* ww w . j a v a 2s. c om*/ 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();/* w w w . ja v a 2 s . c om*/ 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); Type listType = new TypeToken<T>() { }.getType();/* w w w. j a v a2s . co m*/ 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// w w w.j av a 2s . com * * @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); }
From source file:br.com.thiaguten.contrib.JsonContrib.java
License:Apache License
private static void deepJsonArraySearchToJsonArrayFlattened(JsonArray jsonArray, JsonArray jsonArrayFlattened) { if (jsonArray == null || jsonArrayFlattened == null) { throw new IllegalArgumentException("JsonArray and/or JsonArrayFlattened parameter(s) must not be null"); }/* w ww . j ava 2s.c om*/ Iterator<JsonElement> iterator = jsonArray.iterator(); while (iterator.hasNext()) { JsonElement value = iterator.next(); if (value.isJsonObject()) { // Creates new flattened JsonObject instance. JsonObject jsonObjectFlattened = new JsonObject(); // Iterates recursively in JsonObject (value), checking content and populating the flattened JsonObject instance. deepJsonObjectSearchToJsonObjectFlattened((JsonObject) value, jsonObjectFlattened); // Adds the flattened JsonObject instance in the flattened JsonArray instance. jsonArrayFlattened.add(jsonObjectFlattened); } else if (value.isJsonArray()) { deepJsonArraySearchToJsonArrayFlattened((JsonArray) value, jsonArrayFlattened); } else { jsonArrayFlattened.add(value); } } }
From source file:br.ufsc.inf.ine5646.rest.CalculadoraServlet.java
public String handleRequest(String urlParams) { String[] params = urlParams.split("/"); JsonArray ja = new JsonArray(); try {/*from w w w . j a va 2 s . com*/ if (params.length != 3) { ja.add(new JsonPrimitive("erro")); ja.add(new JsonPrimitive("nmero de parmetros incorreto! Exemplo: soma/5/8")); } else if (!params[0].equals("soma") && !params[0].equals("subt") && !params[0].equals("mult") && !params[0].equals("divi")) { ja.add(new JsonPrimitive("erro")); ja.add(new JsonPrimitive("Operao deve ser uma destas: soma,subt,mult,divi")); } else if (params[0].equals("divi") && Double.parseDouble(params[2]) == 0) { ja.add(new JsonPrimitive("erro")); ja.add(new JsonPrimitive("diviso por zero")); } else { double num1 = Double.parseDouble(params[1]); double num2 = Double.parseDouble(params[2]); ja.add(new JsonPrimitive("ok")); switch (params[0]) { case "soma": ja.add(new JsonPrimitive(num1 + num2)); break; case "subt": ja.add(new JsonPrimitive(num1 - num2)); break; case "mult": ja.add(new JsonPrimitive(num1 * num2)); break; case "divi": ja.add(new JsonPrimitive(num1 / num2)); break; default: break; } } } catch (NumberFormatException ex) { ja.add(new JsonPrimitive("erro")); ja.add(new JsonPrimitive(params[1] + " e/ou " + params[2] + " no nmero")); } return ja.toString(); }
From source file:brand.GetBrandMaster.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww .ja v a2 s .c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final DBHelper helper = DBHelper.GetDBHelper(); final Connection dataConnection = helper.getConnMpAdmin(); final JsonObject jResultObj = new JsonObject(); if (dataConnection != null) { try { String sql = "select BRAND_CD,BRAND_NAME,USER_ID from BRANDMST"; PreparedStatement pstLocal = dataConnection.prepareStatement(sql); ResultSet rsLocal = pstLocal.executeQuery(); JsonArray array = new JsonArray(); while (rsLocal.next()) { JsonObject object = new JsonObject(); object.addProperty("BRAND_CD", rsLocal.getString("BRAND_CD")); object.addProperty("BRAND_NAME", rsLocal.getString("BRAND_NAME")); object.addProperty("USER_ID", rsLocal.getInt("USER_ID")); array.add(object); } jResultObj.addProperty("result", 1); jResultObj.addProperty("Cause", "success"); jResultObj.add("data", array); } catch (SQLNonTransientConnectionException ex1) { jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", "Server is down"); } catch (SQLException ex) { jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", ex.getMessage()); } } response.getWriter().print(jResultObj); }
From source file:buri.ddmsence.util.Util.java
License:Open Source License
/** * Converts a list of items into a JSON Array. * //www. j a v a 2s.c o m * @param values the values * @return a JSON array, with the values in the same order */ public static JsonArray getJSONArray(List<?> values) { JsonArray array = new JsonArray(); for (Iterator iterator = values.iterator(); iterator.hasNext();) { Object value = (Object) iterator.next(); if (value instanceof Double) { array.add(new JsonPrimitive((Double) value)); } else if (value instanceof String) { array.add(new JsonPrimitive((String) value)); } else if (value instanceof AbstractBaseComponent) { array.add(((AbstractBaseComponent) value).getJSONObject()); } else { throw new IllegalArgumentException("Unexpected class for JSON property: " + value); } } return (array); }
From source file:business.DataGenerator.java
public String getData(int amount, String properties) { JsonArray names = new JsonArray(); JsonObject person = new JsonObject(); Gson gson = new Gson(); for (int i = 0; i < amount; i++) { person = new JsonObject(); if (properties.contains("fname")) { person.addProperty("fname", fnames.get(new Random().nextInt(6))); }/* www . ja v a 2 s .c o m*/ if (properties.contains("lname")) { person.addProperty("lname", lnames.get(new Random().nextInt(6))); } if (properties.contains("street")) { person.addProperty("street", streets.get(new Random().nextInt(7))); } if (properties.contains("city")) { person.addProperty("city", cities.get(new Random().nextInt(7))); } // System.out.println(i+") "+gson.toJson(person)); names.add(person); } String jsonStr = gson.toJson(names); return jsonStr; }