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:br.com.ifc.util.CarregarListaCores.java

public List<Colors> carregar() throws Exception {
    List<Colors> lista = gson.fromJson(new FileReader(new File(caminho)), new TypeToken<List<Colors>>() {
    }.getType());/*  www  . j  a v  a  2  s.c o  m*/
    return lista;
}

From source file:br.com.locadoraveiculodesktop.recurso.FabricanteRecurso.java

public List<Fabricante> pesquisar(String urlPart) {
    //casa//from   w  ww  . j a v a2s. com
    String targetURL = servidorCasa + "locadoraveiculo/rest/" + urlPart;
    //servio
    //  String targetURL = "http://localhost:2411/locadoraveiculo/rest/" + urlPart;

    List<Fabricante> listaFabricante = new ArrayList<>();

    try {

        URL targetUrl = new URL(targetURL);

        HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("Accept", "application/json");

        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException(
                    "HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
        }

        BufferedReader responseBuffer = new BufferedReader(
                new InputStreamReader((httpConnection.getInputStream())));

        String output;
        System.out.println("Output from Server:  \n");

        while ((output = responseBuffer.readLine()) != null) {
            System.out.println(output);
            TypeToken<List<Fabricante>> token = new TypeToken<List<Fabricante>>() {
            };
            listaFabricante = new Gson().fromJson(output, token.getType());
            System.out.println("listaFabricante " + listaFabricante.size());
        }

        httpConnection.disconnect();

    } catch (IOException | RuntimeException e) {
        System.out.println("erro " + e.getMessage());
    }
    return listaFabricante;
}

From source file:br.com.managedbean.CinemaMB.java

public List<Filme> getFilmesEmCartaz() {
    Client client = Client.create();/*from   w ww .  j  av  a  2  s. c  o  m*/
    WebResource wr = client.resource("http://localhost:8080/Cinema/webresources/filmes");
    String json = wr.get(String.class);
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<List<Filme>>() {
    }.getType());
}

From source file:br.com.notifytec.controllers.AlunoController.java

@Post
@Path("/add")
@Consumes("application/json")
public void add(String nome, String sobrenome, String ra, String cpf, String email, boolean ativo,
        String periodos) {//from w  ww .  j a  v a2  s  .c  o  m
    try {
        Type tipo = new TypeToken<ArrayList<PeriodoSemestre>>() {
        }.getType();
        List<PeriodoSemestre> listaPeriodo = new Gson().fromJson(periodos, tipo);
        AlunoModel aluno = new AlunoModel();
        aluno.setNome(nome);
        aluno.setAtivo(ativo);
        aluno.setSobrenome(sobrenome);
        aluno.setCpf(cpf);
        aluno.setEmail(email);
        aluno.setRa(ra);
        returnSuccess(alunoService.addAlunoService(aluno, listaPeriodo));
    } catch (Exception e) {
        returnError(null, e);
    }
}

From source file:br.com.notifytec.controllers.AlunoController.java

@Post
@Path("/edit")
@Consumes("application/json")
public void edit(String id, String nome, String sobrenome, String ra, String cpf, String email, boolean ativo,
        String usuarioID, String periodos) {
    try {//w  ww .j a  va 2  s .co m
        Type tipo = new TypeToken<ArrayList<PeriodoSemestre>>() {
        }.getType();
        List<PeriodoSemestre> listaPeriodo = new Gson().fromJson(periodos, tipo);
        AlunoModel aluno = new AlunoModel();
        aluno.setId(UUID.fromString(id));
        aluno.setNome(nome);
        aluno.setAtivo(ativo);
        aluno.setSobrenome(sobrenome);
        aluno.setCpf(cpf);
        aluno.setEmail(email);
        aluno.setRa(ra);
        aluno.setUsuarioId(UUID.fromString(usuarioID));
        returnSuccess(alunoService.edit(aluno, listaPeriodo));
    } catch (Exception e) {
        returnError(null, e);
    }
}

From source file:br.com.petshop.caokilate.util.BuscaCepWS.java

public Endereco buscaEndereco(String cep) {
    /*url que ser passada para o webservice que faz o atendimento
     * responde no formato json "cep" ser o cep que ir ser pesquisado
     * na base de dados do viacep.com.br*/
    String url = "http://viacep.com.br/ws/" + cep + "/json";
    try {/*from  www . j  a v  a 2 s  . c o  m*/

        String jsonRetorno = sendGet(url);/*Retorno do webservice*/
        Endereco endereco = new Endereco();
        Gson g = new Gson();
        java.lang.reflect.Type enderecoType = new TypeToken<Endereco>() {
        }.getType();
        endereco = g.fromJson(jsonRetorno, enderecoType);
        return endereco;
    } catch (Exception e) {
        System.out.println("erro na busca do cep");
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:br.com.senac.cantinaclientcustumer.controller.ProductController.java

public ArrayList<Product> listAll() {

    try {// w  ww  .j a  va  2 s  .  com

        Client client = Client.create();
        WebResource webResource = client.resource(URL_PRODUCT_LIST);
        ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);
        Type listType = new TypeToken<ArrayList<Product>>() {
        }.getType();
        ArrayList<Product> produtos = new Gson().fromJson(response.getEntity(String.class), listType);

        return produtos;

    } catch (Exception ex) {
        return null;
    }
}

From source file:br.com.wbrmobile.wsrecicle.resources.PostagemResource.java

@POST
@Consumes(MediaType.APPLICATION_JSON)/*from w  ww  . j a  v a  2  s  .co  m*/
@Path("/inserirpostagem")
public String inserirPostagem(String jsonPostagem) throws Exception {

    Gson gson = new Gson();
    Type postagemType = new TypeToken<Postagem>() {
    }.getType();
    Postagem p = gson.fromJson(jsonPostagem, postagemType);

    ejbFacade.create(p);

    HashMap<String, String> postagemResposta = new HashMap<String, String>();

    postagemResposta.put("estado", CODIGO_EXITO);
    postagemResposta.put("mensagem", "OK");
    postagemResposta.put("id_post", "3");
    JSONObject json = new JSONObject(postagemResposta);
    System.out.println("Json enviado;" + json.toString());
    return json.toString();

}

From source file:br.edu.ifpb.pdm.chat.eventbus.clients.ContactService.java

private List<Chat> getChats(String response, String responseType) {
    String json = response.replaceAll(responseType, "");
    Gson gson = new Gson();
    Type type = new TypeToken<ArrayList<Chat>>() {
    }.getType();//  w w  w.ja  v  a2  s.c  o  m
    return gson.fromJson(json, type);
}

From source file:br.edu.ifrn.pdscfyp.Controller.ProfissionalController.java

@RequestMapping("/mapa")
public String MostrarMapa(HttpSession session, Model model) {
    Usuario u = (Usuario) session.getAttribute("usuarioLogado");

    ArrayList<ArrayList<String>> pontos = new ArrayList<>();

    Client c = Client.create();/*  www  . j  a  v a2 s .c  o m*/
    WebResource wr = c.resource("https://apifyp.herokuapp.com/GetLocalizacoes/");
    String json = wr.get(String.class);

    Gson gson = new Gson();
    pontos = gson.fromJson(json, new TypeToken<List<List<String>>>() {
    }.getType());

    model.addAttribute("usuarioLogado", u);

    model.addAttribute("pontos", pontos);

    return "dashboard";
}