List of usage examples for com.google.gson Gson toJson
public String toJson(JsonElement jsonElement)
From source file:AOP.java
public static void main(String[] args) throws Exception { RequestController rc = new RequestController(); rt = Runtime.instance();/*from w ww . j a va2 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:InventoryDeleteItemServlet.java
License:Open Source License
@Override public HttpResponse doWork(HttpRequest request, String rootDirectory) { HttpResponse response;//from ww w . j a v a 2 s . 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:LanguageServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Define action String action = request.getParameter("action"); //Define data String data = request.getParameter("data"); //Create locale object Locale locale = null;// w w w . j a v a 2 s. c om //Create resource bundle object ResourceBundle resourceBundle = null; //Create key - value pair collection for response Map<String, String> map = new HashMap<String, String>(); //Here i use Gson library for working with Json Gson gson = new GsonBuilder().create(); //Based on action i can switch to different options. //I print predefined text to output just for debugging try { if (action.equals("changeLang")) { if (data.equals("en")) { locale = new Locale("en", "EN"); resourceBundle = ResourceBundle.getBundle("i18n.Bundle", locale); System.out.println(resourceBundle.getString("NAME")); System.out.println(resourceBundle.getString("LAST_NAME")); System.out.println(resourceBundle.getString("LANGUAGE")); } else if (data.equals("ru")) { locale = new Locale("ru", "RU"); resourceBundle = ResourceBundle.getBundle("i18n.Bundle", locale); System.out.println(resourceBundle.getString("NAME")); System.out.println(resourceBundle.getString("LAST_NAME")); System.out.println(resourceBundle.getString("LANGUAGE")); } else if (data.equals("de")) { locale = new Locale("de", "DE"); resourceBundle = ResourceBundle.getBundle("i18n.Bundle", locale); System.out.println(resourceBundle.getString("NAME")); System.out.println(resourceBundle.getString("LAST_NAME")); System.out.println(resourceBundle.getString("LANGUAGE")); } } //Put data to collection.Keys are equals to index.html label's id values. map.put("name", resourceBundle.getString("NAME")); map.put("lastname", resourceBundle.getString("LAST_NAME")); map.put("language", resourceBundle.getString("LANGUAGE")); //Send response to browser. response.getWriter().write(gson.toJson(map)); } catch (Exception e) { e.printStackTrace(); } }
From source file:MainFrame.java
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed Gson gson = new Gson(); String json = gson.toJson(umlDesigner1.getProject()); JFileChooser chooser = new JFileChooser(); if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return;//from www .java 2 s . c o m } File file = chooser.getSelectedFile(); if (file == null) { return; } FileWriter writer = null; try { writer = new FileWriter(file); writer.write(json); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE); } finally { if (writer != null) { try { writer.close(); } catch (IOException x) { } } } }
From source file:RunnerRepository.java
License:Apache License
public static void generateJSon() { JsonObject root = new JsonObject(); JsonObject array = new JsonObject(); array.addProperty("Embedded", "embedded"); array.addProperty("DEFAULT", "Embedded"); JsonObject array2 = new JsonObject(); array2.addProperty("NimbusLookAndFeel", "javax.swing.plaf.nimbus.NimbusLookAndFeel"); array2.addProperty("MetalLookAndFeel", "javax.swing.plaf.metal.MetalLookAndFeel"); array2.addProperty("MotifLookAndFeel", "com.sun.java.swing.plaf.motif.MotifLookAndFeel"); array2.addProperty("WindowsLookAndFeel", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); array2.addProperty("JGoodiesWindowsLookAndFeel", "com.jgoodies.looks.windows.WindowsLookAndFeel"); array2.addProperty("Plastic3DLookAndFeel", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); array2.addProperty("PlasticXPLookAndFeel", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel"); array2.addProperty("DEFAULT", "MetalLookAndFeel"); root.add("plugins", new JsonArray()); root.add("editors", array); root.add("looks", array2); root.add("layout", new JsonObject()); try {//from w w w. j ava 2s.c o m FileWriter writer = new FileWriter(TWISTERINI); Gson gson = new GsonBuilder().setPrettyPrinting().create(); writer.write(gson.toJson(root)); writer.close(); } catch (Exception e) { System.out.println("Could not write default JSon to twister.conf"); e.printStackTrace(); } System.out.println("twister.conf successfully created"); }
From source file:State_Servlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a va 2 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) { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ /* out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet java</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet java at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html*/ try { 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 DISTINCT `State/Union Territory` FROM `india_states_cities` "; PreparedStatement pst = conn.prepareStatement(query); ResultSet rs = pst.executeQuery(); String json; ArrayList<State> listStates = new ArrayList<State>(); while (rs.next()) { State s = new State(); s.setState_name(rs.getString("State/Union Territory")); listStates.add(s); //s.setCity_name(rs.getString("City")); } Gson g = new Gson(); json = g.toJson(listStates); 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:contactDAO.java
@GET @Path("/add") public String addContact(@QueryParam("myEmail") String myEmail, @QueryParam("fEmail") String fEmail) { JsonObject jsonResponse = new JsonObject(); /////// 0. Extract My ID from DB int userID = getUserId(myEmail); if (userID == -1) { //// internal error in DB jsonResponse.addProperty("status", "failed"); jsonResponse.addProperty("result", "Errors with our Servers, Try again later!"); } else {//from w ww . j a v a2 s . com /////// 1. Check if user already exists EntityManager entityManager = entityManagerFactory.createEntityManager(); Query query = entityManager.createNamedQuery("User.findByEmail").setParameter("email", fEmail); List<User> users = query.getResultList(); if (!users.isEmpty()) { /////// 2. if YES ////////////////////////// add to contacts and return POSITIVE response User friend = users.get(0); int friendId = friend.getId(); Contact contact = new Contact(userID, friendId); entityManager.getTransaction().begin(); entityManager.persist(contact); entityManager.getTransaction().commit(); ///// prepare response as JSON jsonResponse.addProperty("status", "success"); Gson gson = new Gson(); jsonResponse.addProperty("result", gson.toJson(friend)); } else { /////// 3. if NO /////////////////////// return user not found NEGATIVE response jsonResponse.addProperty("status", "failed"); jsonResponse.addProperty("result", "Corresponding user is not fount, Check his email"); } } return jsonResponse.toString(); }
From source file:HyperLogLog.java
public String ToJson() { Gson g = new Gson(); JsonObject elm = new JsonObject(); elm.addProperty("M", this.m); elm.addProperty("B", this.b); elm.addProperty("A", this.alpha); JsonArray registerArr = new JsonArray(); for (int i = 0; i < registers.length; i++) { registerArr.add(new JsonPrimitive(registers[i])); }// w w w . ja v a 2 s . c o m elm.add("R", registerArr); return g.toJson(elm); }
From source file:MainPublicacao.java
public static void main(String[] args) { ///////////////////////////feeddenoticia-INSERIR/////////////////////////////////// //esta returnando codigo 204 porem inseri ///*/*from w w w. j av a2 s .c o m*/ String localidade = "centro4"; String descricao = "buraco"; String categoria = "infra-estrutura"; Date data = Date.from(Instant.now()); // long idUsuario = 2; JSONObject jsonObject = new JSONObject(); //Armazena dados em um Objeto JSON jsonObject.put("localidade", localidade); jsonObject.put("descricao", descricao); jsonObject.put("categoria", categoria); jsonObject.put("data", data); //jsonObject.put("idUsuario", idUsuario); Gson gson = new Gson(); String Json = gson.toJson(jsonObject); URL url; try { url = new URL("http://localhost:8084/web/webresources/webService/feed/inserir"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); OutputStream os = connection.getOutputStream(); os.write(Json.getBytes("UTF-8")); os.flush(); int code = connection.getResponseCode(); System.out.println(code + " - " + Json); os.close(); connection.disconnect(); } catch (MalformedURLException ex) { JOptionPane.showMessageDialog(null, "erro de URLException conexao ao rest ( salvar cliente)\n" + ex); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "erro de IOException conexao ao rest ( salvar cliente) \n" + ex); } }
From source file:ListAction.java
@Override public void execute(HttpServletRequest request, PrintWriter out, File folder) { try {/* www . j ava2 s .c o m*/ String type = request.getParameter("type"); JsonArray list = new JsonArray(); switch (type) { case "movie": File[] movies = Service.listAllMovies(folder); for (int i = 0; i < movies.length; i++) { JsonObject m = new JsonObject(); m.addProperty("title", movies[i].getName()); list.add(m); } break; case "series": File[] series = Service.listAllSeries(folder); for (int i = 0; i < series.length; i++) { JsonObject m = new JsonObject(); m.addProperty("title", series[i].getName()); list.add(m); } break; case "episode": String series_title = request.getParameter("series"); folder = new File(folder.getAbsolutePath() + "\\Series\\" + series_title); List<File> episodes = Service.listAllEpisodes(folder); for (File f : episodes) { JsonObject episode = new JsonObject(); String title = f.getName().split(" - ")[0]; episode.addProperty("title", series_title + " - " + title); list.add(episode); } break; } JsonObject container = new JsonObject(); container.add("list", list); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(container); out.println(json); } catch (Exception e) { throw e; } }