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:br.com.thiaguten.contrib.JsonContrib.java

License:Apache License

/**
 * Converts the object to json string without the complexity
 * of relational hierarchy between them, creating a json "flatten".
 *
 * @param object object you wish to converts into a json flatten
 * @return flattened json//w w w  . j  ava2  s .  c om
 */
public static String plainJson(Object object) {
    JsonElement jsonElement = parseObject(object);

    if (jsonElement != null) {
        if (jsonElement.isJsonObject()) {
            JsonObject jsonObjectFlattened = new JsonObject();
            deepJsonObjectSearchToJsonObjectFlattened((JsonObject) jsonElement, jsonObjectFlattened);
            return jsonObjectFlattened.toString();
        } else if (jsonElement.isJsonArray()) {
            JsonArray jsonArrayFlattened = new JsonArray();
            deepJsonArraySearchToJsonArrayFlattened((JsonArray) jsonElement, jsonArrayFlattened);
            return jsonArrayFlattened.toString();
        }
    }
    return getJsonElementAsString(jsonElement);
}

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

License:Apache License

private static void deepJsonObjectSearchToJsonObjectFlattened(JsonObject jsonObject,
        JsonObject jsonObjectFlattened) {
    if (jsonObject == null || jsonObjectFlattened == null) {
        throw new IllegalArgumentException(
                "JsonObject and/or JsonObjectFlattened parameter(s) must not be null");
    }/*w w  w . j a v a 2  s  . c  o m*/

    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();

        if (value.isJsonObject()) {
            deepJsonObjectSearchToJsonObjectFlattened((JsonObject) value, jsonObjectFlattened);
        } else if (value.isJsonArray()) {
            // Creates new flattened JsonArray instance.
            JsonArray jsonArray = new JsonArray();
            // Iterates recursively in JsonArray (value), checking content and populating the flattened JsonArray instance.
            deepJsonArraySearchToJsonArrayFlattened((JsonArray) value, jsonArray);
            // Adds the flattened JsonArray instance in the flattened JsonObject instance.
            jsonObjectFlattened.add(key, jsonArray);
        } else {
            // FIXME - WORKAROUND
            // Attention: A map can not contain duplicate keys. So, the
            // duplicate key is concatenated with a counter, to avoid data
            // loss. I could not think of anything better yet.
            if (jsonObjectFlattened.has(key)) {
                jsonObjectFlattened.add(key + COUNTER.getAndIncrement(), value);
            } else {
                jsonObjectFlattened.add(key, value);
            }
        }
    }
}

From source file:br.edu.ifc.fraiburgo.rubble.servlets.StatusServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setCharacterEncoding("utf8");

    String start = request.getParameter("start");
    String limit = request.getParameter("limit");

    PrintWriter out = response.getWriter();
    response.setContentType("application/json");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET,POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

    boolean sucess = false;
    JsonArray arrayObj = new JsonArray();
    JsonObject myObj = new JsonObject();
    List<Comentario> comments = new ArrayList();
    if (request.getParameter("action").equals("change")) {
        try {/*from  www .j a  va 2 s  . com*/
            Postagem p = new PostagemController()
                    .getPostagemById(Integer.parseInt(request.getParameter("idPostagem")));
            Usuario u = new UsuarioController()
                    .getUsuarioById(Integer.parseInt(request.getParameter("idUsuario")));
            Status s = new Status();
            s.setAtivo(true);
            s.setData(new Date());
            s.setIdPostagem(p);
            s.setIdUsuario(u);
            s.setStatus(request.getParameter("status"));
            s = new StatusController().mergeStatus(s);
            new StatusController().setAllStatusInactive(s.getIdStatus(), p);
            s.setIdPostagem(null);
            s.setIdUsuario(null);
            Gson gson = new Gson();
            JsonElement statusObj = gson.toJsonTree(s);
            myObj.add("status", statusObj);
            sucess = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    myObj.addProperty("success", sucess);
    out.println(myObj.toString());
    out.close();
}

From source file:br.ufsc.inf.ine5646.rest.CalculadoraServlet.java

public String handleRequest(String urlParams) {
    String[] params = urlParams.split("/");
    JsonArray ja = new JsonArray();
    try {//ww w.  jav  a2s. c o  m
        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  . jav  a 2s .c o m
 *
 * @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.
 * //from  w  w w .j a  va  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)));
        }/*from w  w  w . j a  v a  2  s .co  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;
}

From source file:ca.paullalonde.gocd.sns_plugin.executors.NotificationInterestedInExecutor.java

License:Apache License

@Override
public GoPluginApiResponse execute() throws Exception {
    JsonObject jsonObject = new JsonObject();
    JsonArray notifications = new JsonArray();
    notifications.add(REQUEST_STAGE_STATUS.requestName());
    jsonObject.add("notifications", notifications);

    DefaultGoPluginApiResponse defaultGoPluginApiResponse = new DefaultGoPluginApiResponse(200);
    defaultGoPluginApiResponse.setResponseBody(GSON.toJson(jsonObject));
    return defaultGoPluginApiResponse;
}

From source file:ca.ualberta.cs.unter.util.GeoPointConverter.java

License:Apache License

@Override
public JsonElement serialize(GeoPoint src, Type srcType, JsonSerializationContext context) {

    JsonArray array = new JsonArray();

    array.add(context.serialize(src.getLongitudeE6() / 1E6, Double.class));
    array.add(context.serialize(src.getLatitudeE6() / 1E6, Double.class));

    return array;
}

From source file:cashPR.GetCashPaymentHeader.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww  w .  j  a v  a  2s . com*/
 *
 * @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 {
    Connection dataConnection = null;

    final JsonObject jResultObj = new JsonObject();
    final String from_date = request.getParameter("from_date");
    final String to_date = request.getParameter("to_date");
    final String v_type = request.getParameter("v_type");
    final String branch_cd = request.getParameter("branch_cd");
    if (dataConnection == null) {
        dataConnection = helper.getConnMpAdmin();
    }

    if (dataConnection != null) {
        try {
            String sql = "select c.AC_CD,c.REF_NO,VDATE,a.FNAME,c1.BAL,c1.REMARK,c.branch_cd from CPRHD c left join CPRDT c1 on c.REF_NO=c1.REF_NO"
                    + " left join ACNTMST a on c.AC_CD=a.AC_CD where VDATE>=? and VDATE<=? and CTYPE=? ";
            if (!branch_cd.equalsIgnoreCase("0")) {
                sql += " and branch_cd=" + branch_cd;
            }
            sql += " order by VDATE,ref_no";
            PreparedStatement pstLocal = dataConnection.prepareStatement(sql);
            pstLocal.setString(1, from_date);
            pstLocal.setString(2, to_date);
            pstLocal.setString(3, v_type);
            ResultSet rsLocal = pstLocal.executeQuery();
            JsonArray array = new JsonArray();
            while (rsLocal.next()) {
                JsonObject object = new JsonObject();
                object.addProperty("REF_NO", rsLocal.getString("REF_NO"));
                object.addProperty("VDATE", rsLocal.getString("VDATE"));
                object.addProperty("FNAME", rsLocal.getString("FNAME"));
                object.addProperty("BAL", rsLocal.getString("BAL"));
                object.addProperty("REMARK", rsLocal.getString("REMARK"));
                object.addProperty("AC_CD", rsLocal.getString("AC_CD"));
                object.addProperty("BRANCH_CD", rsLocal.getString("BRANCH_CD"));
                array.add(object);
            }
            //                response.getWriter().print(array.toString());
            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);
}