Example usage for com.google.gson Gson fromJson

List of usage examples for com.google.gson Gson fromJson

Introduction

In this page you can find the example usage for com.google.gson Gson fromJson.

Prototype

@SuppressWarnings("unchecked")
public <T> T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException 

Source Link

Document

This method deserializes the Json read from the specified parse tree into an object of the specified type.

Usage

From source file:br.com.rsicarelli.supportlibraryexample.data.WonderPlacesServiceApiImpl.java

License:Apache License

@Override
public void getCachedWonderPlaces(final WonderPlacesServiceCallback<WonderPlaces> callback) {
    AsyncTask<Void, Void, WonderPlaces> asyncTask = new AsyncTask<Void, Void, WonderPlaces>() {
        @Override/*from   w  ww  .  j a  v a 2 s.  co  m*/
        protected WonderPlaces doInBackground(Void... params) {
            InputStream inputStream = ExampleApplication.getExampleApplication().getResources()
                    .openRawResource(R.raw.places);
            final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            Gson gson = new GsonBuilder()
                    .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
                    .serializeNulls().create();

            return gson.fromJson(reader, WonderPlaces.class);
        }

        @Override
        protected void onPostExecute(WonderPlaces places) {
            callback.onLoaded(places);
        }
    };
    asyncTask.execute();
}

From source file:br.com.topsys.cd.applet.AssinaturaApplet.java

public String assinar(String dados) {
    String retorno = null;/* w  w  w . j  a v  a2 s  . com*/

    try {

        X509Certificado certificadoAux = new X509Certificado(Base64.decodeBase64(this.certificado));

        if (certificadoAux.equals(this.certificadoDigital.getX509Certificado())) {

            if (super.flagListaCertificado) {
                Gson gson = new Gson();
                Map<Long, String> map = gson.fromJson(dados, HashMap.class);

                for (Map.Entry<Long, String> entry : map.entrySet()) {
                    entry.setValue(new AssinaturaDigital().assinar(this.certificadoDigital, entry.getValue()));

                }
                retorno = gson.toJson(map);
            } else {
                retorno = new AssinaturaDigital().assinar(this.certificadoDigital, dados);
            }

        } else {

            JOptionPane.showMessageDialog(null, "Certificado digital diferente do usurio do sistema!",
                    "Aviso", JOptionPane.ERROR_MESSAGE);
        }

    } catch (CertificadoDigitalException | ExcecaoX509 ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage(), "Aviso", JOptionPane.ERROR_MESSAGE);
        this.closeError();
    }

    return retorno;

}

From source file:br.com.ufjf.control.main.SystematicLiteratureReviewController.java

/**
 * @return the review//from   w w w  .j a  v a2  s .  c o m
 */
public Review getReview() {
    try {
        String uri = "http://127.0.0.1:8000/api/reviews/vitorfs/effort-estimation-in-global-software-development/";
        URL url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        InputStream json = connection.getInputStream();
        Gson gson = new Gson();
        BufferedReader reader = new BufferedReader(new InputStreamReader(json));
        review = gson.fromJson(reader, Review.class);
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return review;
}

From source file:br.com.virtualVanets.common.util.RestClient.java

public Result sendCommandRest(String ip, Device device, Command command) throws Exception {
    try {/*ww  w .  j  a  va 2  s . co  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/* w  w  w .j  av a2  s.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/*from   w  w  w . j a v a  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.infraVehicle.communication.impl.WebSocket.java

@OnMessage
public String onMessage(String message) {
    //System.out.println("msg "  + message);
    long timeI = System.currentTimeMillis();
    String result = "0";
    try {/*from   ww  w  .  ja v a 2s .  co  m*/
        Gson gson = new Gson();
        Command cmd = gson.fromJson(message, Command.class);
        message = cmd.getCmd();
        //logger.info("onMessage " + peer.getId());
        DeviceActive deviceActive = mapPeersIdSocket.get(peer.getId());
        Device device = deviceActive.getDevice();
        //Checa assinatura
        byte[] data = message.getBytes("UTF8");
        if (ASecurityModel.getInstance().verifySign(device.getPublicKey(), cmd.getSignature(), data)) {
            //logger.info("onMessage " + message);
            SVVListenerDevice listenerDevice = null;
            SVVEventDevice eventDevice = null;
            try {
                message = URLDecoder.decode(message, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (Device.OBU.equalsIgnoreCase(device.getType())) {
                listenerDevice = SVVListenerDevice.getInstance(SVVListenerDevice.LISTENER_VEHICLE);
                eventDevice = SVVEventDevice.getInstance(SVVEventDevice.EVENT_VEHICLE);
                eventDevice.setDevice(device);
                SVVListenerVehicle svvLV = (SVVListenerVehicle) listenerDevice;
                SVVEventVehicle svvEV = (SVVEventVehicle) eventDevice;

                svvEV = readOperationRequestVehicle(message, svvEV);
                svvLV.callEvent(svvEV);
            } else {
                listenerDevice = SVVListenerDevice.getInstance(SVVListenerDevice.LISTENER_INFRA_EQUIPAMENT);
                eventDevice = SVVEventDevice.getInstance(SVVEventDevice.EVENT_INFRA_EQUIPAMENT);
                eventDevice.setDevice(device);
                SVVListenerInfraEquipament svvLIE = (SVVListenerInfraEquipament) listenerDevice;
                SVVEventInfraEquipament svvIE = (SVVEventInfraEquipament) eventDevice;
                svvIE = readOperationRequestInfraEquipament(message, svvIE);
                svvLIE.callEvent(svvIE);
            }
            result = "1";
        }

    } catch (Exception e) {
        e.printStackTrace();
        result = "0";
    }
    //Arquivo de saida do processamento
    long timeF = System.currentTimeMillis();
    try {
        long differ = timeF - timeI;
        StringBuffer sb = new StringBuffer();
        sb.append(sdf.format(new Date(timeI))).append(";").append(message.length()).append(";").append(differ)
                .append(";").append(++cont);
        out.append(sb.toString());
        out.newLine();
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
        try {
            out.append("ERROR: ").append(e.getMessage());
            out.newLine();
        } catch (Exception ex) {
        }
    }
    return result;
}

From source file:br.com.virtualVanets.rest.SVVRest.java

@POST
@Produces(MediaType.APPLICATION_JSON)/*w w  w .  jav a 2  s . com*/
@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/*w  ww  .  j a v  a  2  s  .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("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 ww  w. j  av a 2s.co  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;
}