List of usage examples for com.google.gson GsonBuilder create
public Gson create()
From source file:be.e_contract.eid.android.endpoint.AndroidEndpointServlet.java
License:Open Source License
@Override protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletresponse) throws ServletException, IOException { LOG.debug("doPost"); BeIDOperation operation = getOperation(); if (BeIDOperation.READ_IDENTITY == operation) { Response response = new Response(); response.action = "identity"; PrintWriter printWriter = httpServletresponse.getWriter(); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); printWriter.write(gson.toJson(response)); }/*from w ww . j a v a 2 s . c om*/ }
From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java
License:Open Source License
public static String toJsonString(NeuralNetworkDTO dto, boolean pretty) { JsonObject nn = toJson(dto);/*ww w . ja v a2 s. c o m*/ GsonBuilder builder = new GsonBuilder(); if (pretty) { builder.setPrettyPrinting(); } Gson gson = builder.create(); String output = gson.toJson(nn); return output; }
From source file:be.ugent.tiwi.sleroux.newsrec.recommendationstester.RecommenderAccess.java
public NewsItemCluster[] getRecommendations() { try {/*from w ww .j ava 2 s . c o m*/ String res = doGet(baseUrl + "GetRecommendations.do?count=250&start=0"); GsonBuilder b = new GsonBuilder(); b.registerTypeAdapter(NewsItemCluster.class, new CustomDeserializer()); Gson gson = b.create(); NewsItemCluster[] results = gson.fromJson(res, NewsItemCluster[].class); return results; } catch (IOException ex) { Logger.getLogger(RecommenderAccess.class.getName()).log(Level.SEVERE, null, ex); return new NewsItemCluster[] {}; } }
From source file:be.uza.keratoconus.systemtrayapp.SystemTrayMenu.java
License:Open Source License
private UserPrefsDAO readConfig() { GsonBuilder builder = new GsonBuilder(); builder.enableComplexMapKeySerialization(); Gson gson = builder.create(); Path path = prefsDirPath.resolve(configFilePath); try {/*from w ww . j a v a 2s . c om*/ if (Files.exists(path) && Files.size(path) > 0) { try (InputStream fileInputStream = Files.newInputStream(path)) { final UserPrefsDAO config = gson.fromJson(new InputStreamReader(fileInputStream), UserPrefsDAO.class); return config; } } } catch (IOException ioe) { logService.log(LogService.LOG_WARNING, "Exception thrown when reading user configuration", ioe); } UserPrefsDAO defaultConfig = createDefaultUserConfig(); defaultConfig.animateEnabled = true; defaultConfig.popupsEnabled = true; defaultConfig.displayTimeSeconds = new HashMap<>(); writeConfig(defaultConfig); return defaultConfig; }
From source file:bean.EJBean.java
License:Open Source License
public Edificio getEdificio(String id) { client = ClientBuilder.newClient();/* ww w . j a v a 2s.c o m*/ String edificio = client.target(baseURI).path("edificios").path(id).request(MediaType.APPLICATION_JSON) .get(String.class); client.close(); /// Deserializar/// GsonBuilder gsonBuilder = new GsonBuilder(); JsonDeserializer<Edificio> deserializer = new JsonDeserializer<Edificio>() { @Override public Edificio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); Edificio e = new Edificio(); e.setIdedificio(jsonObject.get("idedificio").getAsString()); if (jsonObject.has("nombreen")) { e.setNombreen(jsonObject.get("nombreen").getAsString()); } if (jsonObject.has("nombrevl")) { e.setNombrevl(jsonObject.get("nombrevl").getAsString()); } if (jsonObject.has("nombrees")) { e.setNombrees(jsonObject.get("nombrees").getAsString()); } if (jsonObject.has("direccion")) { e.setDireccion(jsonObject.get("direccion").getAsString()); } if (jsonObject.has("telefono")) { e.setTelefono(jsonObject.get("telefono").getAsString()); } if (jsonObject.has("enlace")) { e.setEnlace(jsonObject.get("enlace").getAsString()); } e.setXano(jsonObject.get("xano").getAsString()); e.setTopleft(jsonObject.get("topleft").getAsString()); e.setTopright(jsonObject.get("topright").getAsString()); e.setBottomleft(jsonObject.get("bottomleft").getAsString()); // System.out.println("Deserializer: Edi Obj: "+e.toString()); List<Usuario> lu = new ArrayList<Usuario>(); JsonArray usuariosArray = jsonObject.getAsJsonArray("usuarios"); for (JsonElement usuario : usuariosArray) { Usuario u = new Usuario(); JsonObject usuarioObj = usuario.getAsJsonObject(); u.setUsuario(usuarioObj.get("usuario").getAsString()); lu.add(u); } // System.out.println("Deserializer: usu Obj: "+e.toString()); e.setUsuarios(lu); // System.out.println("Deserializer: usu Obj: " + e.getUsuarios().size()); List<Plano> lp = new ArrayList<Plano>(); JsonArray planoArray = jsonObject.getAsJsonArray("planos"); for (JsonElement plano : planoArray) { Plano p = new Plano(); PlanoPK pk = new PlanoPK(); JsonObject planoObj = plano.getAsJsonObject(); pk.setIdedificio(e.getIdedificio()); pk.setIdplano(planoObj.get("idplano").getAsString()); p.setId(pk); p.setEnlace(planoObj.get("enlace").getAsString()); p.setNivel(planoObj.get("nivel").getAsInt()); Edificio edAux = new Edificio(); edAux.setIdedificio(edAux.getIdedificio()); p.setEdificio(edAux); lp.add(p); } e.setPlanos(lp); JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada"); Coordenada coordenada = new Coordenada(); coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString()); coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString()); coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble()); coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble()); e.setCoordenada(coordenada); return e; } }; gsonBuilder.registerTypeAdapter(Edificio.class, deserializer); System.out.println("GSON" + edificio); Gson customGson = gsonBuilder.create(); Edificio jsonToEdificio = customGson.fromJson(edificio, Edificio.class); System.out.print("Size users EJB: " + jsonToEdificio.getUsuarios().size()); return jsonToEdificio; }
From source file:bean.EJBean.java
License:Open Source License
public Espacio getEspacio(String id) { client = ClientBuilder.newClient();// w w w.j a v a 2 s . c om String espacio = client.target(baseURI).path("espacios").path(id).request(MediaType.APPLICATION_JSON) .get(String.class); client.close(); /// Deserializar/// // System.out.println(espacio); GsonBuilder gsonBuilder = new GsonBuilder(); JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() { @Override public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); Espacio e = new Espacio(); e.setIdespacio(jsonObject.get("idespacio").getAsString()); if (jsonObject.has("nombreen")) { e.setNombreen(jsonObject.get("nombreen").getAsString()); } if (jsonObject.has("nombrevl")) { e.setNombrevl(jsonObject.get("nombrevl").getAsString()); } if (jsonObject.has("nombrees")) { e.setNombrees(jsonObject.get("nombrees").getAsString()); } if (jsonObject.has("bloque")) { e.setBloque(jsonObject.get("bloque").getAsString()); } if (jsonObject.has("piso")) { e.setPiso(jsonObject.get("piso").getAsInt()); } if (jsonObject.has("tipo")) { e.setTipo(jsonObject.get("tipo").getAsString()); } e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean()); if (jsonObject.has("boundingbox")) { e.setBoundingbox(jsonObject.get("boundingbox").getAsString()); } // System.out.println("Deserializer: Edi Obj: "+e.toString()); JsonObject edificioObj = jsonObject.getAsJsonObject("edificio"); Edificio edificio = new Edificio(); edificio.setIdedificio(edificioObj.get("idedificio").getAsString()); e.setEdificio(edificio); List<Panorama> lp = new ArrayList<Panorama>(); JsonArray panoArray = jsonObject.getAsJsonArray("panoramas"); for (JsonElement pano : panoArray) { Panorama p = new Panorama(); JsonObject panoObj = pano.getAsJsonObject(); p.setIdpanorama(panoObj.get("idpanorama").getAsString()); p.setEnlace(panoObj.get("enlace").getAsString()); lp.add(p); } e.setPanoramas(lp); JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada"); Coordenada coordenada = new Coordenada(); coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString()); coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString()); coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble()); coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble()); e.setCoordenada(coordenada); if (jsonObject.has("profesores")) { List<Profesor> lprof = new ArrayList<Profesor>(); JsonArray profArray = jsonObject.getAsJsonArray("profesores"); for (JsonElement prof : profArray) { Profesor p = new Profesor(); JsonObject profObj = prof.getAsJsonObject(); p.setIdprofesor(profObj.get("idprofesor").getAsString()); p.setUsuario(profObj.get("usuario").getAsString()); p.setVisibilidad(profObj.get("visibilidad").getAsBoolean()); lprof.add(p); } e.setProfesores(lprof); } return e; } }; gsonBuilder.registerTypeAdapter(Espacio.class, deserializer); // System.out.println("GSON"+espacio); Gson customGson = gsonBuilder.create(); Espacio jsonToEspacio = customGson.fromJson(espacio, Espacio.class); return jsonToEspacio; }
From source file:bean.EJBean.java
License:Open Source License
public List<Espacio> getEspaciosFromEdificio(String id) { client = ClientBuilder.newClient();/*from w w w. j av a 2 s . com*/ String espaciosJSON = client.target(baseURI).path("edificios").path(id).path("espacios") .request(MediaType.APPLICATION_JSON).get(String.class); client.close(); GsonBuilder gsonBuilder = new GsonBuilder(); JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() { @Override public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { JsonObject jsonObject = json.getAsJsonObject(); Espacio e = new Espacio(); // System.out.println("HOLA "+jsonObject.get("bloque").getAsString()); e.setIdespacio(jsonObject.get("idespacio").getAsString()); e.setNombrees(jsonObject.get("nombrees").getAsString()); // e.setNombreen(jsonObject.get("nombreen").getAsString()); // e.setNombrevl(jsonObject.get("nombrevl").getAsString()); e.setBloque(jsonObject.get("bloque").getAsString()); e.setBoundingbox(jsonObject.get("boundingbox").getAsString()); e.setPiso(jsonObject.get("piso").getAsInt()); e.setTipo(jsonObject.get("tipo").getAsString()); e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean()); JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada"); Coordenada coordenada = new Coordenada(); coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString()); coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString()); coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble()); coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble()); e.setCoordenada(coordenada); JsonObject edificioObj = jsonObject.getAsJsonObject("edificio"); Edificio edificio = new Edificio(); edificio.setIdedificio(edificioObj.get("idedificio").getAsString()); /* * edificio.setNombrees(edificioObj.get("nombrees").getAsString()); * edificio.setNombreen(edificioObj.get("nombreen").getAsString()); * edificio.setNombrevl(edificioObj.get("nombrevl").getAsString()); * edificio.setEnlace(edificioObj.get("enlace").getAsString()); * edificio.setXano(edificioObj.get("xano").getAsString()); * edificio.setTopleft(edificioObj.get("topleft").getAsString()); * edificio.setTopright(edificioObj.get("topright").getAsString()); * edificio.setBottomleft(edificioObj.get("bottomleft").getAsString()); */ e.setEdificio(edificio); List<Panorama> lu = new ArrayList<Panorama>(); JsonArray panoramaArray = jsonObject.getAsJsonArray("panoramas"); for (JsonElement panorama : panoramaArray) { Panorama p = new Panorama(); JsonObject panoramaObj = panorama.getAsJsonObject(); p.setIdpanorama(panoramaObj.get("idpanorama").getAsString()); p.setEnlace(panoramaObj.get("enlace").getAsString()); if (panoramaObj.has("panorama")) { p.setPanorama(panoramaObj.get("panorama").getAsInt()); } lu.add(p); } e.setPanoramas(lu); List<Profesor> lp = new ArrayList<Profesor>(); if (jsonObject.has("profesores")) { JsonArray profesorArray = jsonObject.getAsJsonArray("profesores"); for (JsonElement profesor : profesorArray) { Profesor p = new Profesor(); JsonObject profesorObj = profesor.getAsJsonObject(); p.setIdprofesor(profesorObj.get("idprofesor").getAsString()); p.setUsuario(profesorObj.get("usuario").getAsString()); p.setVisibilidad(profesorObj.get("visibilidad").getAsBoolean()); lp.add(p); } } e.setProfesores(lp); return e; } }; gsonBuilder.registerTypeAdapter(Espacio.class, deserializer); Type listType = new TypeToken<List<Espacio>>() { }.getType(); Gson customGson = gsonBuilder.create(); List<Espacio> jsonToEspacios = customGson.fromJson(espaciosJSON, listType); // System.out.println("Success Espacio: "+ jsonToEspacios.size()); return jsonToEspacios; }
From source file:bi.sms_delivery.java
public String sendSms(SMSHolder sh) throws Exception { Responce res;/*from ww w. ja va2s.c o m*/ /*MobakDocBiulder mdb = MobakDocBiulder.getInstance("NerudTorg", "4Ro21sPc"); Document doc = mdb.createDocument(sh); URLRequester urlreq = new URLRequester(MobakDocBiulder.URL, "utf8"); urlreq.setPostMethod(); urlreq.addPostParameter("xml", primXml.documentToString(doc)); urlreq.create();*/ DiscontDocBuilder ddb = DiscontDocBuilder.getInstance("330krasn0907", "134087"); JSONObject requestBody = ddb.createDiscontJSONRequest(sh); URL url = new URL(DiscontDocBuilder.URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); wr.write(requestBody.toString()); wr.flush(); String str; StringBuilder sb = new StringBuilder(); int HttpResult = con.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); //System.out.println("" + sb.toString()); str = sb.toString(); } else { //System.out.println(con.getResponseMessage()); addError(con.getResponseMessage()); str = con.getResponseMessage(); } URLRequester urlreq = new URLRequester(DiscontDocBuilder.URL, "utf8"); //urlreq.setPostMethod(); GsonBuilder gb = new GsonBuilder(); Gson gson = gb.create(); //map.put("mes", "330krasn0907"); //String body="{\"login\":\"330krasn0907\",\"password\":\"134087\",\"clientId\":\"1234\",\"phone\":\"+79124850319\",\"text\":\"test\"}"; //urlreq.addPostParameter("login", "330krasn0907"); //urlreq.addPostParameter("password", "134087"); //urlreq.addPostParameter("messages", requestBody); //urlreq.setUrlEncoding("UTF-8"); //urlreq.addPostParameter("json",gson.toJson(map)); //urlreq.create(); String resp = urlreq.getResult(); Type maptype = new TypeToken<HashMap<String, String>>() { }.getType(); HashMap<String, String> urlres = gson.fromJson(resp, maptype); /*String str; if (urlreq.getErrors().isEmpty() && !urlres.get("status").equals("error")) { //str = "success " + urlreq.getResult(); str = " ? "; //str+=" "+requestBody.toString()+"; res="+urlreq.getResult()+";"; log(sh); } else { str = "error " + urlreq.getErrors().toString() + "; url_responce_description: " + urlres.get("description") + "; req_text=" + requestBody.toString() + "; res="; for (String s : urlres.keySet()) { str += s + " - " + urlres.get(s) + "; "; } }*/ return str; }
From source file:blobstoretest.DownloadServlet.java
License:Apache License
/** * Serves a file by means a blobKey./*from www . j av a 2 s.co m*/ */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String blobKey = req.getParameter("blobKey"); if (blobKey == null) { ErrorResponse error = new ErrorResponse(); error.setCode(HttpServletResponse.SC_BAD_REQUEST); ErrorMessage message = new ErrorMessage(); message.setMessage("The Blobkey parameter is required"); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.setContentType("application/json"); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); resp.getWriter().print(gson.toJson(error)); } else { blobstore.serve(new BlobKey(blobKey), resp); } }
From source file:blobstoretest.OAuthFilter.java
License:Apache License
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try {// w w w .j a v a2 s. c om oauth.getCurrentUser(); chain.doFilter(req, res); } catch (OAuthRequestException e) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); HttpServletResponse httpRes = (HttpServletResponse) res; httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpRes.setContentType("application/json"); ErrorResponse error = new ErrorResponse(); error.setCode(HttpServletResponse.SC_UNAUTHORIZED); ErrorMessage message = new ErrorMessage(); message.setMessage("This service requires authentication"); httpRes.getWriter().print(gson.toJson(error)); } }