Example usage for com.google.gson.reflect TypeToken TypeToken

List of usage examples for com.google.gson.reflect TypeToken TypeToken

Introduction

In this page you can find the example usage for com.google.gson.reflect TypeToken TypeToken.

Prototype

@SuppressWarnings("unchecked")
protected TypeToken() 

Source Link

Document

Constructs a new type literal.

Usage

From source file:backend.ws.PatientWS.java

public List<Patient> getPatientsByHealthProfessional(int id) {
    List<Patient> pList = null;

    List<NameValuePair> params = new ArrayList<>(); //array com os params necessrios para registar um terapeuta
    params.add(new BasicNameValuePair("idHealthProfessional", String.valueOf(id)));

    try {/*from  w  ww  .  j  a v a  2s  .c  o m*/
        responseWS = wrapperWS.sendRequest("Patient", "getPatientsByHealthProfessional", params); //efetua o pedido ao WS
        String jsonResp = wrapperWS.readResponse(responseWS); //Passa a responseWS para uma string

        int httpResponseCod = responseWS.getStatusLine().getStatusCode();
        if (httpResponseCod != 200) {
            Validation v = gson.fromJson(jsonResp, Validation.class); //Converso do objecto Json para o objecto Java
            log.error("\n\tCod: " + v.getCod() + "\tMsg: " + v.getMsg());
            throw new RuntimeException("Ocorreu um erro ao aceder aos dados do Paciente");
        }

        Type type = new TypeToken<List<Patient>>() {
        }.getType(); //tipo do para o qual queros retornar a responseWS Json
        pList = gson.fromJson(jsonResp, type);

    } catch (RuntimeException e) {
        log.error("\n\t" + e.getMessage());
        throw new RuntimeException(e.getMessage());
    }
    log.debug("\n\tPatient data access success");
    log.debug("\n\tPs : " + pList.toString());
    return pList;
}

From source file:backend.ws.SubDomainWS.java

public List<SubDomain> getSubDomainByDomain(int idD) {
    List<SubDomain> sdList = null;

    List<NameValuePair> params = new ArrayList<>(); //array com os params necessrios para registar um terapeuta
    params.add(new BasicNameValuePair("idDomain", String.valueOf(idD)));

    try {/*  w  ww.jav a  2 s  .  co  m*/
        responseWS = wrapperWS.sendRequest("SubDomain", "getSubDomainByDomain", params); //efetua o pedido ao WS
        String jsonResp = wrapperWS.readResponse(responseWS); //Passa a responseWS para uma string

        int httpResponseCod = responseWS.getStatusLine().getStatusCode();
        if (httpResponseCod != 200) {
            Validation v = gson.fromJson(jsonResp, Validation.class); //Converso do objecto Json para o objecto Java     
            log.error("\n\tCod: " + v.getCod() + "\tMsg: " + v.getMsg());
            throw new RuntimeException("Ocorreu um erro ao aceder aos dados do SubDomnio");
        }

        Type type = new TypeToken<List<SubDomain>>() {
        }.getType(); //tipo do para o qual queros retornar a responseWS Json
        sdList = gson.fromJson(jsonResp, type);

    } catch (RuntimeException e) {
        log.error("\n\t" + e.getMessage());
        throw new RuntimeException(e.getMessage());
    }
    log.debug("\n\tSubDomain data access success");
    log.debug("\n\tPs : " + sdList.toString());
    return sdList;
}

From source file:bank.AddUpdateBankVoucher.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w ww  . ja  v a 2 s  . 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 {
    final String detailJson = request.getParameter("detail");
    TypeToken<List<BankPaymentReceiptModel>> token = new TypeToken<List<BankPaymentReceiptModel>>() {
    };
    List<BankPaymentReceiptModel> detail = new Gson().fromJson(detailJson, token.getType());
    response.getWriter().print(saveVoucher((ArrayList<BankPaymentReceiptModel>) detail));

}

From source file:bd.ac.seu.jsondemo.Main.java

public static void readFromURL() {
    try {/*from   w w  w . java 2 s. co m*/
        URL url = new URL(
                "http://my.seu.ac.bd/~kmhasan/__WebServices/spring2017aj/schedule_section_json.php?semester=45");
        InputStream inputStream = url.openStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line = bufferedReader.readLine();

        Gson gson = new GsonBuilder().create();

        Type sectionsListType = new TypeToken<List<Section>>() {
        }.getType();
        List<Section> sectionsList = gson.fromJson(line, sectionsListType);

        sectionsList.forEach(System.out::println);
    } catch (MalformedURLException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:bd.ac.seu.midtermq4.Main.java

public void readJson() {
    Gson gson = new GsonBuilder().create();
    try {//w  w  w. j a  va  2  s  .  c om
        URL url = new URL("http://my.seu.ac.bd/~kmhasan/sculptures.json");
        InputStream inputStream = url.openStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String jsonString = "";
        String line;
        while ((line = bufferedReader.readLine()) != null)
            jsonString += line.trim();
        System.out.println("JSON input = [" + jsonString + "]");

        Type sculpturesListType = new TypeToken<List<Sculpture>>() {
        }.getType();
        List<Sculpture> sculpturesList = gson.fromJson(jsonString, sculpturesListType);

        sculpturesList.forEach(System.out::println);

    } catch (MalformedURLException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:bean.EJBean.java

License:Open Source License

public List<Usuario> getListaUsuarios() {

    client = ClientBuilder.newClient();// w  ww . ja v a2 s.c  om

    String usuarios = client.target(baseURI).path("usuarios").request(MediaType.APPLICATION_JSON)
            .get(String.class);

    client.close();

    // System.out.println("METHOD2 "+usuarios);

    Type listType = new TypeToken<List<Usuario>>() {
    }.getType();
    List<Usuario> jsonToUsuarioList = new Gson().fromJson(usuarios, listType);

    return jsonToUsuarioList;

}

From source file:bean.EJBean.java

License:Open Source License

public List<String> getNombresUsuarios() {

    client = ClientBuilder.newClient();//from www .  j a  v a 2s .co  m

    String usuarios = client.target(baseURI).path("usuarios").path("nombres")
            .request(MediaType.APPLICATION_JSON).get(String.class);

    client.close();

    // System.out.println("METHOD2 "+usuarios);

    Type listType = new TypeToken<List<String>>() {
    }.getType();
    List<String> jsonToUsuarioList = new Gson().fromJson(usuarios, listType);

    return jsonToUsuarioList;

}

From source file:bean.EJBean.java

License:Open Source License

public List<String> getNombresEdificios() {
    client = ClientBuilder.newClient();//from www .  j ava  2s.c  o  m
    String edificios = client.target(baseURI).path("edificios").path("nombres")
            .request(MediaType.APPLICATION_JSON).get(String.class);
    client.close();

    Type listType = new TypeToken<List<String>>() {
    }.getType();
    List<String> jsonToEspacioList = new Gson().fromJson(edificios, listType);

    return jsonToEspacioList;
}

From source file:bean.EJBean.java

License:Open Source License

public List<Edificio> getListaEdificios() {

    client = ClientBuilder.newClient();/*  w  ww .j a v  a  2 s  .co m*/
    String edificios = client.target(baseURI).path("edificios").request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    Type listType = new TypeToken<List<Edificio>>() {
    }.getType();
    List<Edificio> jsonToEdificioList = new Gson().fromJson(edificios, listType);

    return jsonToEdificioList;
}

From source file:bean.EJBean.java

License:Open Source License

public List<Edificio> getListaEdificiosEditor(String id) {
    System.out.println("EJB Bean: " + userMB.isUserAdmin());
    client = ClientBuilder.newClient();/*from  w ww. j ava  2s .c om*/
    String edificios = client.target(baseURI).path("usuarios").path(id).path("edificios")
            .request(MediaType.APPLICATION_JSON).get(String.class);
    client.close();

    Type listType = new TypeToken<List<Edificio>>() {
    }.getType();
    List<Edificio> jsonToEdificioList = new Gson().fromJson(edificios, listType);

    return jsonToEdificioList;
}