List of usage examples for com.google.gson Gson Gson
public Gson()
From source file:WSClient.java
public Response doRequest(String path, Object object) throws IOException { Response response = null;/*ww w .j a v a2 s.c om*/ try { URL url = new URL(BASE_URL + path); System.out.println("##### utl : " + BASE_URL + path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); //String input = "{\"qty\":100,\"name\":\"iPad 4\"}"; Gson gson = new Gson(); String input = gson.toJson(object); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); /*if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); }*/ BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder content = new StringBuilder(""); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); content.append(output); } conn.disconnect(); System.out.println(" content :" + content.toString()); response = gson.fromJson(content.toString(), Response.class); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; }
From source file:ListImages.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { try {/*from w ww . j ava 2s . c om*/ emf = Persistence.createEntityManagerFactory("FileUploadPU"); em = emf.createEntityManager(); List<String> list = new ArrayList<String>(); List<Date> uploadTime = new ArrayList<Date>(); for (Imagenew i : (List<Imagenew>) em.createNamedQuery("Imagenew.findAll").getResultList()) { list.add(i.getPath()); uploadTime.add(i.getUploaddate()); } String json = new Gson().toJson(list); out.write(json); } catch (Exception e) { System.out.println(e); } finally { em.close(); emf.close(); } } }
From source file:PokemonServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www . ja v a 2 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 { try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ Connection con = ConBD.getConnection(); if (con == null) { throw new SQLException("Erro conectando"); } Gson gson = new Gson(); Statement stm = con.createStatement(); Pokemon pokemon = new Pokemon(); pokemon.setNome(request.getParameter("txt-nome")); pokemon.setCp(request.getParameter("txt-cp")); pokemon.setGen(request.getParameter("txt-gen")); pokemon.setCandy(request.getParameter("txt-candy")); out.println(pokemon.getNome()); String insert = "INSERT INTO pokemon (nome,cp,gen,candy)" + "VALUES(?, ?, ?, ?)"; PreparedStatement preparedStatement = con.prepareStatement(insert); preparedStatement.setString(1, pokemon.getNome()); preparedStatement.setString(2, pokemon.getCp()); preparedStatement.setString(3, pokemon.getGen()); preparedStatement.setString(4, pokemon.getCandy()); preparedStatement.executeUpdate(); } catch (SQLException ex) { } catch (Exception e) { } }
From source file:CompaniesEditor.java
public String toJson(Map<Integer, Company> companies) { Gson gson = new Gson(); String json = gson.toJson(companies); return json; }
From source file:InventoryAddNewItemServlet.java
License:Open Source License
@Override public HttpResponse doWork(HttpRequest request, String rootDirectory) { HttpResponse response;/* w w w . j av a 2 s .c o m*/ try { String inventoryUrl = "./web/inventory.json"; File inventory = new File(inventoryUrl); StringBuilder sb = new StringBuilder(); Scanner sc = new Scanner(inventory); while (sc.hasNext()) { sb.append(sc.nextLine()); } sc.close(); // Add this new book to the list of existing books Gson gson = new Gson(); InventoryObject[] inventoryArray = gson.fromJson(sb.toString(), InventoryObject[].class); ArrayList<InventoryObject> inventoryList = new ArrayList<InventoryObject>( Arrays.asList(inventoryArray)); String body = new String(request.getBody()); System.out.println(body); String[] newItem = body.split("&"); // Add new item int id, quant; String name; try { id = Integer.parseInt(newItem[0].split("=")[1]); name = newItem[1].split("=")[1].replace("+", " "); quant = Integer.parseInt(newItem[2].split("=")[1]); } catch (Exception e) { return HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } InventoryObject item = new InventoryObject(id, name, quant); if (quant < 0) { return HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } for (InventoryObject existingItem : inventoryList) { if (existingItem.getID() == id) { return HttpResponseFactory.create400BadRequest(Protocol.CLOSE); } } inventoryList.add(item); // Serialize new list Gson gsonBuilder = new GsonBuilder().setPrettyPrinting().create(); String arrayListToJson = gsonBuilder.toJson(inventoryList); BufferedWriter bw = new BufferedWriter(new FileWriter(inventory)); bw.write(arrayListToJson); bw.close(); response = HttpResponseFactory.create200OK(inventory, Protocol.CLOSE); } catch (Exception e) { response = HttpResponseFactory.create404NotFound(Protocol.CLOSE); } return response; }
From source file:servletAjaxCadastro.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww. j a v a 2s . co 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 { response.setContentType("text/html;charset=UTF-8"); String action = request.getParameter("acao"); if ("cpf".equals(action)) { try (PrintWriter out = response.getWriter()) { //out.println(action); ClienteDao clienteDao = new ClienteDao(); /* TODO output your page here. You may use following sample code. */ String cpf = request.getParameter("cpf"); Cliente cliente = new Cliente(); cliente.setCpf(cpf); String json; if (clienteDao.verificaCpf(cliente)) { json = new Gson().toJson("CPF ja cadastrado!"); } else { json = new Gson().toJson("Ok"); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } } if ("login".equals(action)) { try (PrintWriter out = response.getWriter()) { ClienteDao clienteDao = new ClienteDao(); String login = request.getParameter("login"); Cliente cliente = new Cliente(); cliente.setCpf(login); String json; if (clienteDao.verificaLogin(cliente)) { json = new Gson().toJson("Login ja cadastrado!"); } else { json = new Gson().toJson("Ok"); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } } }
From source file:CompanyController.java
public static <T extends Object> T fromJson(String json, Class<T> classe) { Gson gson = new Gson(); gson.fromJson(json, classe);// w ww.j av a 2 s. c o m return gson.fromJson(json, classe); }
From source file:CompanyController.java
public static String toJson(Object value) { Gson gson = new Gson(); String json = gson.toJson(value); return json; }
From source file:City_Servlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w. ja v a 2 s . 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 { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { try { String state = request.getParameter("state"); String JDBC_driver = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost:3306/wheels_on_rent"; Class.forName(JDBC_driver); String db_user = "root"; String db_pass = ""; Connection conn = DriverManager.getConnection(DB_URL, db_user, db_pass); String query = "SELECT `City` FROM `india_states_cities` WHERE" + "`State/Union Territory` =? AND `City` IS NOT NULL"; PreparedStatement pst = conn.prepareStatement(query); pst.setString(1, state); ResultSet rs = pst.executeQuery(); String json; ArrayList<City> listCity = new ArrayList<City>(); if (!rs.next()) { out.print("rs is null"); } while (rs.next()) { City c = new City(); c.setCity_name(rs.getString("City")); listCity.add(c); } Gson g = new Gson(); json = g.toJson(listCity); out.print(json); rs.close(); pst.close(); conn.close(); } catch (Exception ex) { out.print("error" + ex.getMessage()); } } catch (IOException ex) { Logger.getLogger(State_Servlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:CommentServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ try {//from w w w . j av a 2 s. c o m emf = Persistence.createEntityManagerFactory("FileUploadPU"); em = emf.createEntityManager(); List<String> list = new ArrayList<String>(); for (Commentnew i : (List<Commentnew>) em.createNamedQuery("Commentnew.findAll").getResultList()) { list.add(i.getText()); } String json2 = new Gson().toJson(list); out.write(json2); } catch (Exception e) { System.out.println(e); } finally { em.close(); emf.close(); } } }