Example usage for com.google.gson Gson toJson

List of usage examples for com.google.gson Gson toJson

Introduction

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

Prototype

public String toJson(JsonElement jsonElement) 

Source Link

Document

Converts a tree of JsonElement s into its equivalent JSON representation.

Usage

From source file:br.com.winget.cadele.WebserviceUser.java

@POST
@Path("login")
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public String userLogin(@FormParam("email") String email, @FormParam("senha") String senha) {
    UsuarioDAO userDao = new UsuarioDAO();
    int id = userDao.getUserLogin(email, senha);
    if (id != 0) {
        Usuario user = userDao.getUserById(id);
        Gson gson = new Gson();
        return gson.toJson(user);
    }//from   w ww  .  ja v a 2 s  .  co m
    return "{null}";
}

From source file:br.com.winget.cadele.WebserviceUser.java

/**
 * POST method for updating or creating an instance of WebserviceUser
 * @param nome/*from   w  w w. j  a  v  a2s .co  m*/
 * @param email
 * @param senha
 * @return an HTTP response with content of the updated or created resource.
 */
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public String insertUser(@FormParam("nome") String nome, @FormParam("email") String email,
        @FormParam("senha") String senha) {
    Usuario user = new Usuario();
    Gson gson = new Gson();
    int id;
    UsuarioDAO userDao = new UsuarioDAO();
    user.setNome(nome);
    user.setEmail(email);
    user.setSenha(senha);
    user.setAtivo(1);
    id = userDao.insert(user);
    user.setId(id);
    LocalizacaoDAO localDao = new LocalizacaoDAO();
    Localizacao local = new Localizacao();
    local.setLongitude(0);
    local.setLatitude(0);
    local.setAltitude(0);
    local.setIdUser(id);
    localDao.insert(local);
    return gson.toJson(user);
}

From source file:br.com.ws.ClinicaOdontologicaWS.java

@GET
@Produces("application/json")
@Path("Usuario/get/{login}")
public String getUsuario(@PathParam("login") String login) {

    Usuario u = new Usuario(); // Cria Usuario
    u.setNm_login(login); // Envia o Login para o objeto

    UsuarioDAO dao = new UsuarioDAO(); // Instancia Usuario DAO
    u = dao.buscar(u); // Faz a busca do usuario no Banco

    // Converter para Json
    Gson g = new Gson();
    return g.toJson(u); // retorn o Json do Usuario

}

From source file:br.com.ws.ClinicaOdontologicaWS.java

@GET
@Produces("application/json")
@Path("Usuario/list")
public String listaUsuario() {

    List<Usuario> lista = new ArrayList<Usuario>();

    UsuarioDAO dao = new UsuarioDAO();
    lista = dao.listar();/*  ww w .ja va 2 s. c om*/

    System.out.println(lista);
    // Converter para Json
    Gson g = new Gson();
    return g.toJson(lista);
}

From source file:br.cwi.crescer.Pessoa.Listar.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//www . j  a v a  2  s . 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 {

    PessoaRepositorio repositorio = new PessoaRepositorio();
    Gson gson = new Gson();
    response.setContentType("application/json");

    try (PrintWriter out = response.getWriter();) {
        out.print(gson.toJson(repositorio.listar()));
        out.flush();
    }
}

From source file:br.edu.ifpb.bdnc.daos.PesquisaDao.java

@Override
public String add(Pesquisa p) {
    String s = agora.toEpochMilli() + "key";
    Jedis jedis = new Jedis("127.0.0.1", 6379);
    Gson gson = new Gson();
    jedis.set(s, gson.toJson(p));
    return s;//ww w .  jav  a 2 s .  c om

}

From source file:br.edu.ifpb.node1.Programa.java

public static void main(String[] args) throws Exception {
    Pessoa p = new Pessoa("111.111.111-11", "Laerton Marques de Figueiredo");
    Gson gson = new Gson();
    String mensagem = gson.toJson(p);
    String retorno = ConexSocket.enviaMensagem(mensagem, PORTANODE2, HOST);
    System.out.println(retorno);/*  www  .  j  av a 2  s  . c  o m*/
}

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

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  w w.jav  a  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();
    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.ifrn.pdscfyp.Model.Profissional.java

public static void addProfissional(Profissional p) {
    Client c = Client.create();//  ww  w. j a  va2 s.  co  m

    Gson gson = new Gson();

    WebResource wr = c.resource("https://apifyp.herokuapp.com/AdicionarProfissional");

    ClientResponse cr = wr.accept("application/json").type("application/json").post(ClientResponse.class,
            gson.toJson(p));
}

From source file:br.edu.ifrn.pdscfyp.Model.Usuario.java

public static void addUsuario(Usuario u) {
    Client c = Client.create();//from ww  w  . ja  v a  2s .c  o m

    Gson gson = new Gson();

    WebResource wr = c.resource("https://apifyp.herokuapp.com/AdicionarUsuario");

    ClientResponse cr = wr.accept("application/json").type("application/json").post(ClientResponse.class,
            gson.toJson(u));
}