Example usage for com.google.gson JsonObject JsonObject

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

Introduction

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

Prototype

JsonObject

Source Link

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/*from ww  w  . jav a 2 s  .co m*/
 */
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 deepJsonArraySearchToJsonArrayFlattened(JsonArray jsonArray, JsonArray jsonArrayFlattened) {
    if (jsonArray == null || jsonArrayFlattened == null) {
        throw new IllegalArgumentException("JsonArray and/or JsonArrayFlattened parameter(s) must not be null");
    }//from  ww  w. j  a v  a 2s . co m

    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.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  ww  w  .  ja  v a 2 s . c  o  m
            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.edu.ifpe.garanhuns.pos.sysadvogacia.controladores.ControladorAdvogadoServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w  w  w. j a  va2  s  .  co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userPath = request.getServletPath();
    NegocioAdvogado negocioAdvogado = new NegocioAdvogado();
    Advogado advogado;

    if (userPath.equals("/SalvarAdvogado")) {
        advogado = new Advogado();
        if (!request.getParameter("codigo").isEmpty()) {
            advogado.setCodigo(Integer.parseInt(request.getParameter("codigo")));
        } else {
            advogado.setCodigo(0);
        }
        advogado.setNome(request.getParameter("nome"));
        advogado.setCpf(request.getParameter("cpf"));
        advogado.setOab(request.getParameter("oab"));
        advogado.setEndereco(request.getParameter("endereco"));
        advogado.setTelefone(request.getParameter("telefone"));

        String json = new Gson().toJson(negocioAdvogado.salvar(advogado));
        response.getWriter().print(json);

    }

    if (userPath.equals("/ListarAdvogados")) {
        String json = new Gson().toJson(negocioAdvogado.listarAdvogados());
        response.getWriter().print(json);
    }

    if (userPath.equals("/RemoverAdvogado")) {
        String id = request.getParameter("id");
        advogado = negocioAdvogado.advogadoPorCodigo(Integer.parseInt(id));
        negocioAdvogado.remover(advogado);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("success", "true");
        response.getWriter().print(new Gson().toJson(jsonObject));
    }

}

From source file:br.edu.ifpe.garanhuns.pos.sysadvogacia.controladores.ControladorClienteServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww w  .  j  a v  a 2 s  .  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userPath = request.getServletPath();
    NegocioCliente negocioCliente = new NegocioCliente();
    Cliente cliente;

    if (userPath.equals("/SalvarCliente")) {
        cliente = new Cliente();
        if (!request.getParameter("codigo").isEmpty()) {
            cliente.setCodigo(Integer.parseInt(request.getParameter("codigo")));
        } else {
            cliente.setCodigo(0);
        }
        cliente.setNome(request.getParameter("nome"));
        cliente.setCpfCnpj(request.getParameter("cpfCnpj"));
        cliente.setEndereco(request.getParameter("endereco"));
        cliente.setTelefone(request.getParameter("telefone"));

        String json = new Gson().toJson(negocioCliente.salvar(cliente));
        response.getWriter().print(json);

    }

    if (userPath.equals("/ListarClientes")) {
        Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

            public boolean shouldSkipClass(Class<?> clazz) {
                return (clazz == Processo.class);
            }

            /**
             * Custom field exclusion goes here
             */
            public boolean shouldSkipField(FieldAttributes f) {
                return false;
            }

        })
                /**
                 * Use serializeNulls method if you want To serialize null
                 * values By default, Gson does not serialize null values
                 */
                .serializeNulls().create();

        String json = gson.toJson(negocioCliente.listarClientes());
        response.getWriter().print(json);
    }

    if (userPath.equals("/RemoverCliente")) {
        JsonObject jsonObject = new JsonObject();
        try {
            String id = request.getParameter("id");
            cliente = negocioCliente.clientePorCodigo(Integer.parseInt(id));
            negocioCliente.remover(cliente);
            jsonObject.addProperty("success", "true");
            response.getWriter().print(new Gson().toJson(jsonObject));
        } catch (RemoverClienteComProcessosException e) {
            jsonObject.addProperty("errorMsg", e.mensagem());
            response.getWriter().print(new Gson().toJson(jsonObject));
        }

    }

}

From source file:br.edu.ifpe.garanhuns.pos.sysadvogacia.controladores.ControladorLeiServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w.  jav  a2s. 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
 */

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

    String userPath = request.getServletPath();

    NegocioLei negocioLei = new NegocioLei();

    Processo proc = new Processo();
    proc.setCodigo(1);

    Lei lei;

    if (userPath.equals("/SalvarLei")) {

        lei = new Lei();

        if (!request.getParameter("codigo").isEmpty()) {
            lei.setCodigo(Integer.parseInt(request.getParameter("codigo")));
        } else {
            lei.setCodigo(0);
        }
        lei.setArtigo(Integer.parseInt(request.getParameter("artigo")));
        lei.setDescricao(request.getParameter("descricao"));
        lei.setTipo(request.getParameter("tipo"));
        lei.setCapitulo(Integer.parseInt(request.getParameter("capitulo")));

        lei.setProcessoCodigo(proc);

        String json = new Gson().toJson(negocioLei.salvar(lei));

        response.getWriter().print(json);
    }

    if (userPath.equals("/ListarLeis")) {
        String json = new Gson().toJson(negocioLei.listarLeis());
        response.getWriter().print(json);
    }
    if (userPath.equals("/RemoverLei")) {
        String id = request.getParameter("id");
        lei = negocioLei.LeiPorCodigo(Integer.parseInt(id));
        negocioLei.remover(lei);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("sucess", "true");
        response.getWriter().print(new Gson().toJson(jsonObject));
    }

}

From source file:br.edu.ifpe.garanhuns.pos.sysadvogacia.controladores.ControladorProcessoServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  www .j a  va 2s  .c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userPath = request.getServletPath();
    NegocioProcesso negocioProcesso = new NegocioProcesso();
    Processo processo;

    if (userPath.equals("/SalvarProcesso")) {
        processo = new Processo();
        if (!request.getParameter("codigo").isEmpty()) {
            processo.setCodigo(Integer.parseInt(request.getParameter("codigo")));
        }

        processo.setDataAbertura(new Date(request.getParameter("dataAbertura")));
        processo.setInstanciaAtual(request.getParameter("instanciaAtual"));
        processo.setStatus(Integer.parseInt(request.getParameter("status")));
        processo.setDecisaoFinal(request.getParameter("decisaoFinal"));
        processo.setDescricao(request.getParameter("descricao"));

        String json = new Gson().toJson(negocioProcesso.salvar(processo));
        response.getWriter().print(json);

    }

    if (userPath.equals("/ListarProcessos")) {
        String json = new Gson().toJson(negocioProcesso.listarProcessos());
        response.getWriter().print(json);
    }

    if (userPath.equals("/RemoverProcesso")) {
        String id = request.getParameter("id");
        processo = negocioProcesso.processoPorCodigo(Integer.parseInt(id));
        negocioProcesso.remover(processo);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("success", "true");
        response.getWriter().print(new Gson().toJson(jsonObject));
    }

}

From source file:br.ufg.inf.es.saep.sandbox.dominio.infraestrutura.ValorSerializer.java

License:Creative Commons License

@Override
public JsonElement serialize(Valor valor, Type type, JsonSerializationContext jsonSerializationContext) {
    JsonObject obj = new JsonObject();
    byte tipo = valor.getTipo();

    obj.addProperty("tipo", tipo);
    switch (tipo) {
    case REAL:// w  w w. ja  va  2s .  co m
        obj.addProperty("valor", valor.getReal());
        break;
    case Valor.LOGICO:
        obj.addProperty("valor", valor.getBoolean());
        break;
    case Valor.DATA:
        obj.addProperty("valor", valor.getData().format(Valor.FORMATO_DATA));
        break;
    case Valor.STRING:
        obj.addProperty("valor", valor.getString());
        break;
    }

    return obj;
}

From source file:br.unicamp.cst.bindings.soar.JSoarCodelet.java

License:Open Source License

public JsonObject createJson(String pathToLeaf, Object value) {
    JsonObject json = new JsonObject();
    Class a = value.getClass();//from www. j  a  v a  2  s .c  om
    if (a == String.class) {
        String specvalue = (String) value;
        json = getJsoar().createJsonFromString(pathToLeaf, specvalue);
    } else if (a == double.class) {
        double specvalue = (double) value;
        json = getJsoar().createJsonFromString(pathToLeaf, specvalue);
    }
    return json;
}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public JsonObject getOutputLinkJSON() {
    JsonObject json = new JsonObject();
    try {//from  w  ww .  ja v a 2  s.  c o m
        if (getAgent() != null) {
            List<Wme> Commands = getOutputLink_WME();
            setOutputLinkAsString(getWMEStringOutput());
            for (Wme command : Commands) {
                String commandType = command.getAttribute().toString();
                json.add(commandType, new JsonObject());
                String parameter = command.getAttribute().toString();
                String parvalue = command.getValue().toString();
                Iterator<Wme> children = command.getChildren();
                while (children.hasNext()) {
                    Wme child = children.next();
                    parameter = child.getAttribute().toString();
                    parvalue = child.getValue().toString();
                    Float floatvalue = tryParseFloat(parvalue);
                    if (floatvalue != null) {
                        json.get(commandType).getAsJsonObject().addProperty(parameter, floatvalue);
                    } else {
                        json.get(commandType).getAsJsonObject().addProperty(parameter, parvalue);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.severe("Error while creating SOAR Kernel" + e);
    }
    setJsonOutputLinkAsString(json.toString());
    return (json);
}