List of usage examples for com.google.gson GsonBuilder GsonBuilder
public GsonBuilder()
From source file:br.com.tamarozzi.dao.impl.UsuarioDaoImpl.java
public UsuarioDaoImpl() { this.gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting() .create(); }
From source file:br.com.virtualVanets.common.util.RestClient.java
public Result sendCommandRest(String ip, Device device, Command command) throws Exception { try {/*from ww w . jav a2 s. c o m*/ HttpClient httpclient = new DefaultHttpClient(); Gson gson = new GsonBuilder().setDateFormat(OperationRequestDevice.PARTTERN_DATE).create(); String jsonDevice = gson.toJson(device); String jsonCommand = gson.toJson(command); StringBuffer sbUrl = new StringBuffer(ip); // Encode url, para tratar os caracteres do padro JSON, tipo o '{' e '}' //jsonDevice = URLEncoder.encode(jsonDevice, "UTF-8"); //jsonCommand = URLEncoder.encode(jsonCommand, "UTF-8"); //sbUrl.append(jsonDevice).append(",").append(jsonCommand); //System.out.println("url " + sbUrl); System.out.println("IP " + ip); HttpPost httpPost = new HttpPost(ip); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("device", jsonDevice)); params.add(new BasicNameValuePair("cmd", jsonCommand)); // httpPost.setEntity(new StringEntity(gson.toJson(device))); //params.add(new StringEntity(gson.toJson(device))); //params.add(new StringEntity(gson.toJson(command))); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); //HttpResponse httpResponse = httpclient.execute(new HttpGet(sbUrl.toString())); //HttpResponse httpResponse = httpclient.execute(new HttpPost(sbUrl.toString())); HttpResponse httpResponse = httpclient.execute(httpPost); // receive response as inputStream String resultJson = ""; try { InputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if (inputStream != null) { resultJson = convertInputStreamToString(inputStream); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); throw e; } System.out.println("json " + resultJson); Result result = gson.fromJson(resultJson, Result.class); return result; } catch (Exception e) { // TODO: handle exception throw e; } }
From source file:br.com.virtualVanets.infraVehicle.communication.impl.WebSocket.java
/** * L os parametros da requisio e passa para o objeto do Evento * * @param message//from w ww . j a v a2s . c o m * @param svvEV * @return */ private SVVEventVehicle readOperationRequestVehicle(String message, SVVEventVehicle svvEV) { Gson gson = new GsonBuilder().setDateFormat(OperationRequestDevice.PARTTERN_DATE).create(); //OperationRequestVehicle orv = (OperationRequestVehicle) gson.fromJson(message, OperationRequestVehicle.class); //System.out.println("Vehicle: " + message); SVVEventVehicle svvEVTemp = (SVVEventVehicle) gson.fromJson(message, svvEV.getClass()); svvEV.getDevice().setAltitude(svvEVTemp.getDevice().getAltitude()); svvEV.getDevice().setLatitude(svvEVTemp.getDevice().getLatitude()); svvEV.getDevice().setLongitude(svvEVTemp.getDevice().getLongitude()); svvEV.getDevice().setSpeed(svvEVTemp.getDevice().getSpeed()); svvEV.getDevice().setDirection(svvEVTemp.getDevice().getDirection()); svvEV.getDevice().setSpeed(svvEVTemp.getDevice().getSpeed()); svvEVTemp.setDevice(svvEV.getDevice()); //svvEV.setAltitude(orv.getAltitude()); //svvEV.setLatitude(orv.getLatitude()); //svvEV.setLongitude(orv.getLongitude()); //svvEV.setSpeed(orv.getSpeed()); //svvEV.setOperationCode(orv.getOperationCode()); //svvEV.setDate(orv.getDate()); //svvEV.setMessage(orv.getMessage()); return svvEVTemp; }
From source file:br.com.virtualVanets.infraVehicle.communication.impl.WebSocket.java
/** * L os parametros da requisio e passa para o obujeto Evento * * @param message//www . j ava 2 s . c o m * @param svvIE * @return */ private SVVEventInfraEquipament readOperationRequestInfraEquipament(String message, SVVEventInfraEquipament svvIE) { Gson gson = new GsonBuilder().setDateFormat(OperationRequestDevice.PARTTERN_DATE).create(); //OperationRequestInfraEquipament orv = (OperationRequestInfraEquipament) gson.fromJson(message, OperationRequestInfraEquipament.class); //System.out.println("Infra: " + message); SVVEventInfraEquipament svvIETemp = (SVVEventInfraEquipament) gson.fromJson(message, svvIE.getClass()); svvIE.getDevice().setAltitude(svvIETemp.getDevice().getAltitude()); svvIE.getDevice().setLatitude(svvIETemp.getDevice().getLatitude()); svvIE.getDevice().setLongitude(svvIETemp.getDevice().getLongitude()); svvIE.getDevice().setMoisture(svvIETemp.getDevice().getMoisture()); svvIE.getDevice().setPressure(svvIETemp.getDevice().getPressure()); svvIE.getDevice().setTemperature(svvIETemp.getDevice().getTemperature()); svvIETemp.setDevice(svvIE.getDevice()); //InfraEquipament infraEquipament = (InfraEquipament)svvIETemp.getDevice(); //svvIE.setAltitude(orv.getAltitude()); //svvIE.setLatitude(orv.getLatitude()); //svvIE.setLongitude(orv.getLongitude()); //svvIE.setMoisture(orv.getMoisture()); //svvIE.setPressure(orv.getPressure()); //svvIE.setOperationCode(orv.getOperationCode()); //svvIE.setTemperature(orv.getTemperature()); //svvIE.setDate(orv.getDate()); //svvIE.setMessage(orv.getMessage()); return svvIETemp; }
From source file:br.com.virtualVanets.rest.SVVRest.java
@POST @Produces(MediaType.APPLICATION_JSON)/*from w ww .j a v a 2s . c o m*/ @Path("/sendCommandDevice/") public String sendCommandDevice(@FormParam("device") String device, @FormParam("cmd") String cmd) { Gson gson = new GsonBuilder().setDateFormat(OperationRequestDevice.PARTTERN_DATE).create(); System.out.println("sendCommandDevice"); Command command = gson.fromJson(cmd, Command.class); Device deviceObj = gson.fromJson(device, Vehicle.class); Result result = SVVWS.sendCommand(deviceObj, command); String resultJson = new Gson().toJson(result); return resultJson; }
From source file:br.com.virtualVanets.routingAlgorithm.Network.java
/** * L os parametros da requisio e passa para o objeto do Evento * * @param message// ww w. j a v a 2s . co m * @param svvEV * @return */ private SVVEventVehicle readOperationRequestVehicle(String message, SVVEventVehicle svvEV) { Gson gson = new GsonBuilder().setDateFormat(OperationRequestDevice.PARTTERN_DATE).create(); // OperationRequestVehicle orv = (OperationRequestVehicle) gson.fromJson(message, OperationRequestVehicle.class); System.out.println("Send MSG Vehicle: " + message); SVVEventVehicle svvEVTemp = (SVVEventVehicle) gson.fromJson(message, svvEV.getClass()); svvEVTemp.setDevice(svvEV.getDevice()); //svvEV.setAltitude(orv.getAltitude()); //svvEV.setLatitude(orv.getLatitude()); //svvEV.setLongitude(orv.getLongitude()); //svvEV.setSpeed(orv.getSpeed()); //svvEV.setOperationCode(orv.getOperationCode()); //svvEV.setDate(orv.getDate()); //svvEV.setMessage(orv.getMessage()); return svvEVTemp; }
From source file:br.com.virtualVanets.routingAlgorithm.Network.java
/** * L os parametros da requisio e passa para o objeto Evento * * @param message/*from w w w . ja v a2s . c o m*/ * @param svvIE * @return */ private SVVEventInfraEquipament readOperationRequestInfraEquipament(String message, SVVEventInfraEquipament svvIE) { Gson gson = new GsonBuilder().setDateFormat(OperationRequestDevice.PARTTERN_DATE).create(); //OperationRequestInfraEquipament orv = (OperationRequestInfraEquipament) gson.fromJson(message, OperationRequestInfraEquipament.class); System.out.println("Send MSG Infra: " + message); SVVEventInfraEquipament svvIETemp = (SVVEventInfraEquipament) gson.fromJson(message, svvIE.getClass()); svvIETemp.setDevice(svvIE.getDevice()); //svvIE.setAltitude(orv.getAltitude()); //svvIE.setLatitude(orv.getLatitude()); //svvIE.setLongitude(orv.getLongitude()); //svvIE.setMoisture(orv.getMoisture()); //svvIE.setPressure(orv.getPressure()); //svvIE.setOperationCode(orv.getOperationCode()); //svvIE.setTemperature(orv.getTemperature()); //svvIE.setDate(orv.getDate()); //svvIE.setMessage(orv.getMessage()); return svvIETemp; }
From source file:br.edu.ifpe.garanhuns.pos.sysadvogacia.controladores.ControladorClienteServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w w w . ja v a 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 { 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.unochapeco.unoheartserver.util.CustomGsonBuilder.java
public static Gson getInstance() { if (gson == null) { gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, (JsonSerializer<LocalDate>) new JsonSerializer<LocalDate>() { @Override/* w w w . j a v a 2 s .com*/ public JsonElement serialize(LocalDate t, java.lang.reflect.Type type, JsonSerializationContext jsc) { if (t != null) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); return new JsonPrimitive(t.format(dateTimeFormatter)); } else { return null; } } }).registerTypeAdapter(LocalDate.class, (JsonDeserializer<LocalDate>) new JsonDeserializer<LocalDate>() { @Override public LocalDate deserialize(JsonElement je, java.lang.reflect.Type type, JsonDeserializationContext jdc) { if (je.getAsJsonPrimitive().getAsString() != null) { return LocalDate.parse( je.getAsJsonPrimitive().getAsString().substring(0, 10).trim(), DateTimeFormatter.ofPattern("yyyy-MM-dd")); } else { return null; } } }) .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) new JsonSerializer<LocalDateTime>() { @Override public JsonElement serialize(LocalDateTime t, java.lang.reflect.Type type, JsonSerializationContext jsc) { if (t != null) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter .ofPattern("yyyy-MM-dd'T'HH:mm:ss"); return new JsonPrimitive(t.format(dateTimeFormatter)); } else { return null; } } }) .registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (JsonElement je, java.lang.reflect.Type type, JsonDeserializationContext jdc) -> { if (je.getAsJsonPrimitive().getAsString() != null) { return LocalDateTime.parse(je.getAsJsonPrimitive().getAsString().trim(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")); } else { return null; } }).create(); } return gson; }
From source file:br.gov.jfrj.siga.ex.bl.ExBL.java
License:Open Source License
public String toJSON(ExMobil mobil) throws Exception { // Prune// w w w . jav a2 s . c om ExMobil mob = (ExMobil) getImplementationDeep(mobil); // mob.setExDocumento((ExDocumento) // Objeto.getImplementation(mob.doc())); mob.setExDocumentoFilhoSet(null); // mob.setExMarcaSet(null); mob.setExMovimentacaoReferenciaSet(null); mob.setExMovimentacaoSet(null); mob.setExTipoMobil(null); ExDocumento doc = mob.doc(); // doc.setCadastrante(null); // doc.setDestinatario(null); doc.setExBoletimDocSet(null); doc.setExClassificacao(null); doc.setExDocAnterior(null); doc.setExFormaDocumento(null); doc.setExMobilAutuado(null); doc.setExMobilPai(null); doc.setExMobilSet(null); doc.setExModelo(null); doc.setExNivelAcesso(null); // doc.setExTipoDocumento(null); // doc.getExTipoDocumento().setExFormaDocumentoSet(null); doc.setLotaCadastrante(null); doc.setLotaDestinatario(null); // doc.setLotaSubscritor((DpLotacao) // Objeto.getImplementation(doc.getLotaSubscritor())); // doc.setLotaSubscritor(null); // doc.setLotaTitular(null); // doc.setCadastrante(null); // doc.setDestinatario(null); // doc.setSubscritor(null); // doc.setTitular(null); // doc.setOrgaoExterno(null); // doc.setOrgaoExternoDestinatario(null); // doc.setOrgaoUsuario(null); ObjetoBaseSerializer hps = new ObjetoBaseSerializer(); Gson gson = new GsonBuilder().registerTypeAdapter(java.sql.Blob.class, new BlobSerializer()) // .registerTypeAdapter(ObjetoBase.class, hps) .setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); hps.setGson(gson); String jsonOutput = gson.toJson(mob); // Importante para que as alteraes do "prune" no sejam salvas no BD. dao().getSessao().clear(); return jsonOutput; }