List of usage examples for com.google.gson Gson Gson
public Gson()
From source file:GetCommenterServlet.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 ww . ja v a 2s .co m*/ emf = Persistence.createEntityManagerFactory("FileUploadPU"); em = emf.createEntityManager(); List<String> commenter = new ArrayList<String>(); for (Commentnew i : (List<Commentnew>) em.createNamedQuery("Commentnew.findAll").getResultList()) { commenter.add(i.getCommenter()); } String json = new Gson().toJson(commenter); out.write(json); } catch (Exception e) { System.out.println(e); } finally { em.close(); emf.close(); } } }
From source file:Servlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//ww 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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Connection connection = null; SQLConnect msql = new SQLConnect(); Gson gson = new Gson(); JsonElement jsonElmnt; JsonArray jsonArr; ArrayList<Alumnos> alumn = new ArrayList<Alumnos>(); connection = msql.conectar(); alumn = msql.getListaAlumn(connection); //Codigo y nombre de los alumnos listados jsonElmnt = gson.toJsonTree(alumn); jsonArr = jsonElmnt.getAsJsonArray(); response.setContentType("application/json"); response.getWriter().print(jsonArr); } catch (SQLException ex) { Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Servlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w. j ava 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 { try { String code = request.getParameter("code"); Connection connection = null; SQLConnect msql = new SQLConnect(); Gson gson = new Gson(); String jsonElmnt; Alumnos alumn = new Alumnos(); connection = msql.conectar(); alumn = msql.getAssigTutorias(connection, Integer.parseInt(code)); jsonElmnt = gson.toJson(alumn); response.setContentType("application/json"); response.getWriter().print(jsonElmnt); } catch (SQLException ex) { Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:RawCollectionsExample.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { Gson gson = new Gson(); Collection collection = new ArrayList(); collection.add("hello"); collection.add(5);//from w ww .jav a2 s . c o m collection.add(new Event("GREETINGS", "guest")); String json = gson.toJson(collection); System.out.println("Using Gson.toJson() on a raw collection: " + json); JsonParser parser = new JsonParser(); JsonArray array = parser.parse(json).getAsJsonArray(); String message = gson.fromJson(array.get(0), String.class); int number = gson.fromJson(array.get(1), int.class); Event event = gson.fromJson(array.get(2), Event.class); System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message, number, event); }
From source file:Exportador.java
public static void escribir(String nombreDeArchivo, Agenda agenda) { FileWriter fichero = null;/*from w ww . j a va2 s . c o m*/ PrintWriter pw = null; Gson gson = new Gson(); String JSON = gson.toJson(agenda); try { fichero = new FileWriter(nombreDeArchivo); pw = new PrintWriter(fichero); pw.print(JSON); } catch (Exception e) { e.printStackTrace(); } finally { try { // Nuevamente aprovechamos el finally para // asegurarnos que se cierra el fichero. if (null != fichero) fichero.close(); } catch (Exception e2) { e2.printStackTrace(); } } }
From source file:AOP.java
public static void main(String[] args) throws Exception { RequestController rc = new RequestController(); rt = Runtime.instance();/*www . j a v a 2 s. c om*/ World world = new World(); int prisonerCount = 8; String[] prisonerNames = { "Randy", "Stan", "Kyle", "Eric", "Kenny", "Chef", "Butters", "MrMackey" }; createContainer(); Random rand = new Random(System.currentTimeMillis()); Gson gson = new Gson(); String json = gson.toJson(world); rc.sendPostReq(0, json); try { for (int i = 0; i < prisonerCount; i++) { Object[] agentArgs = new Object[3]; agentArgs[0] = world; agentArgs[1] = world.getRooms().get(0); agentArgs[2] = new Point(rand.nextInt(199), rand.nextInt(199)); mainContainer.createNewAgent(prisonerNames[i], "aop.agents.Prisoner", agentArgs).start(); } } catch (StaleProxyException ex) { Logger.getLogger(AOP.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:iosActivityListener.java
public UserActivity strToActivity(String json) { Gson gson = new Gson(); GsonMessage gsonMessage;/*from w w w .ja v a2 s . c om*/ gsonMessage = gson.fromJson(json, GsonMessage.class); if (gsonMessage.flag.equals("true")) { Flag flag = new Flag(new User(gsonMessage.user_id, gsonMessage.channel_name)); return flag; } else { Date date = new Date(gsonMessage.time); System.out.println("Date: " + date.toString()); Message message = new Message(gsonMessage.message, new User(gsonMessage.user_id, gsonMessage.channel_name), date, gsonMessage.channel_name); return message; } }
From source file:crearVenta.java
License:Open Source License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www . j a va2 s .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"); try (PrintWriter out = response.getWriter()) { HttpSession ses = request.getSession(); GestoSAT gestor = (GestoSAT) ses.getAttribute("gestor"); Cliente cli; int idCliente = Integer.parseInt(request.getParameter("id")); Gson gJson = new Gson(); Map material = (HashMap) gJson.fromJson(request.getParameter("material"), HashMap.class); // Parse JSON if (idCliente > 0) { cli = gestor.getCliente(idCliente); } else { cli = new Cliente(request.getParameter("cliente[nombre]"), request.getParameter("cliente[apellidos]"), request.getParameter("cliente[NIF]"), request.getParameter("cliente[provincia]"), request.getParameter("cliente[poblacion]"), Integer.parseInt(request.getParameter("cliente[cp]")), request.getParameter("cliente[calle]"), request.getParameter("cliente[numero]"), request.getParameter("cliente[escalera]"), Integer.parseInt(request.getParameter("cliente[piso]")), request.getParameter("cliente[puerta]"), Integer.parseInt(request.getParameter("cliente[tlfFijo]")), Integer.parseInt(request.getParameter("cliente[tlfMovil]")), request.getParameter("cliente[email]"), request.getParameter("cliente[observaciones]"), gestor); idCliente = gestor.crearCliente(cli); } out.print(gestor.crearVenta(idCliente, new Albaran(request.getParameter("concepto"), request.getParameter("entrega[provEntrega]"), request.getParameter("entrega[pobEntrega]"), Integer.parseInt(request.getParameter("entrega[cpEntrega]")), request.getParameter("entrega[calleEntrega]"), request.getParameter("entrega[numEntrega]"), request.getParameter("entrega[escaleraEntrega]"), Integer.parseInt(request.getParameter("entrega[pisoEntrega]")), request.getParameter("entrega[puertaEntrega]"), material, request.getParameter("observaciones"), cli, gestor))); } }
From source file:InventoryDeleteItemServlet.java
License:Open Source License
@Override public HttpResponse doWork(HttpRequest request, String rootDirectory) { HttpResponse response;//from ww w .j a v a 2s .co 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); // Find existing item and remove it int id = Integer.parseInt(body.split("=")[1]); for (InventoryObject item : inventoryList) { if (item.getID() == id) { inventoryList.remove(item); break; } } // 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:saveChangeAlbaran.java
License:Open Source License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* www . ja va2s. 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 { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { HttpSession ses = request.getSession(); GestoSAT gestor = (GestoSAT) ses.getAttribute("gestor"); Gson gJson = new Gson(); Map empleados = (HashMap) gJson.fromJson(request.getParameter("10"), HashMap.class); // Parse JSON Map material = (HashMap) gJson.fromJson(request.getParameter("11"), HashMap.class); // Parse JSON int idAlbaran = Integer.parseInt(request.getParameter("12")); Albaran albaran = gestor.getAlbaran(idAlbaran); out.print(albaran.actualizar(idAlbaran, request.getParameter("8"), request.getParameter("0"), request.getParameter("1"), Integer.parseInt(request.getParameter("2")), request.getParameter("3"), request.getParameter("4"), request.getParameter("5"), Integer.parseInt(request.getParameter("6")), request.getParameter("7"), empleados, material, request.getParameter("9"))); } }