Atualizado pela última vez em 26/12/2024
Salve galerinhaaa, tudo bem com vocês?
Hoje vou mostrar para vocês uma biblioteca feita em JAVA desenvolvida pela Google. Ela serve para poder fazer a Serialização / Desserialização de JSON de uma forma bem simples e intuitiva. Bom parar de enrolação e vamos botar a mão na massa.
Introdução
JSON, em seu significado teórico é “Javascript Object Notation”, do qual nada mais é que o formato mais leve conhecido por mim de transferência/intercâmbio de dados. Ele é similar ao XML, e tem a mesma utilidade e mesmo intuito, porém é mais leve. O detalhe é que não necessariamente, apesar do nome, você tem que usá-lo com Javascript.
GSON é uma biblioteca Java que pode ser usada para converter objetos Java em sua representação JSON. Ele também pode ser usado para converter uma string JSON em um objeto Java equivalente. Com a GSON, você pode trabalhar com objetos Java arbitrários, incluindo objetos pré-existentes que você não possui código-fonte.
Modo de Utilização
Antes de começarmos a “codar”, temos que importar a biblioteca no nosso projeto. Podemos importar baixando o .jar através desse link ou utilizando o Apache Maven igual o código abaixo :
<dependency> | |
<groupId>com.google.code.gson</groupId> | |
<artifactId>gson</artifactId> | |
<version>2.8.1</version> | |
</dependency> |
Ou se preferir pode utilizar o Gradle/Grails
dependencies { | |
... | |
compile 'com.google.code.gson:gson:2.8.1' | |
... | |
} |
Exemplos
Vamos utilizar aqui um exemplo de pedidos de vendas. Onde temos o pedido, itens do pedido, e o cliente que fez o pedido. Essa estrutura em JSON ficaria mais ou menos assim:
Estrutura JSON
{ | |
"id": 1234, | |
"cliente": { | |
"id": 24, | |
"nome": "Guilherme Haynes Howe" | |
}, | |
"itens": [ | |
{ | |
"id": 1, | |
"descricao": "Cerveja Brahma Litrão", | |
"qtd": 6 | |
}, | |
{ | |
"id": 2, | |
"descricao": "Mendorato 500g", | |
"qtd": 2 | |
}, | |
{ | |
"id": 3, | |
"descricao": "Paçoquita caixa com 24", | |
"qtd": 12 | |
} | |
] | |
} |
Pedido.java
Analisando toda essa estrutura JSON vemos que temos um ID do pedido, o cliente que fez o pedido, e os itens do pedido. Logo essa será nossa classe Pedido, e a estrutura dela será essa abaixo:
Lembrando que todos os nomes das chaves do JSON tem que ser iguais as encontradas nas classes
/* | |
* Copyright (C) 2017 haynes | |
* | |
* This program is free software: you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation, either version 3 of the License, or | |
* (at your option) any later version. | |
* | |
* This program is distributed in the hope that it will be useful, | |
* but WITHOUT ANY WARRANTY; without even the implied warranty of | |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
* GNU General Public License for more details. | |
* | |
* You should have received a copy of the GNU General Public License | |
* along with this program. If not, see <http://www.gnu.org/licenses/>. | |
*/ | |
package gsonexample.pedido; | |
import gsonexample.cliente.Cliente; | |
import gsonexample.pedido.itens.ItemPedido; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* | |
* @author haynes | |
*/ | |
public class Pedido { | |
private int id; | |
private Cliente cliente; | |
private List<ItemPedido> itens; | |
public Pedido() { | |
itens = new ArrayList<>(); | |
} | |
public int getId() { | |
return id; | |
} | |
public void setId(int id) { | |
this.id = id; | |
} | |
public Cliente getCliente() { | |
return cliente; | |
} | |
public void setCliente(Cliente cliente) { | |
this.cliente = cliente; | |
} | |
public List<ItemPedido> getItens() { | |
return itens; | |
} | |
public void setItens(List<ItemPedido> itens) { | |
this.itens = itens; | |
} | |
} |
Cliente.java
Agora vamos analisar a estrutura do cliente, vemos que temos id e nome do nosso cliente, então ela ficaria mais ou menos assim:
/* | |
* Copyright (C) 2017 haynes | |
* | |
* This program is free software: you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation, either version 3 of the License, or | |
* (at your option) any later version. | |
* | |
* This program is distributed in the hope that it will be useful, | |
* but WITHOUT ANY WARRANTY; without even the implied warranty of | |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
* GNU General Public License for more details. | |
* | |
* You should have received a copy of the GNU General Public License | |
* along with this program. If not, see <http://www.gnu.org/licenses/>. | |
*/ | |
package gsonexample.cliente; | |
/** | |
* | |
* @author haynes | |
*/ | |
public class Cliente { | |
private int id; | |
private String nome; | |
public int getId() { | |
return id; | |
} | |
public void setId(int id) { | |
this.id = id; | |
} | |
public String getNome() { | |
return nome; | |
} | |
public void setNome(String nome) { | |
this.nome = nome; | |
} | |
} |
ItemPedido.java
Agora analisando a lista de pedidos, vemos que temos um id, uma descrição do produto, e a quantidade de cada pedido. Pensando nisso ficaria mais ou menos assim nossa estrutura:
/* | |
* Copyright (C) 2017 haynes | |
* | |
* This program is free software: you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation, either version 3 of the License, or | |
* (at your option) any later version. | |
* | |
* This program is distributed in the hope that it will be useful, | |
* but WITHOUT ANY WARRANTY; without even the implied warranty of | |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
* GNU General Public License for more details. | |
* | |
* You should have received a copy of the GNU General Public License | |
* along with this program. If not, see <http://www.gnu.org/licenses/>. | |
*/ | |
package gsonexample.pedido.itens; | |
/** | |
* | |
* @author haynes | |
*/ | |
public class ItemPedido { | |
private int id; | |
private String descricao; | |
private int qtd; | |
public int getId() { | |
return id; | |
} | |
public void setId(int id) { | |
this.id = id; | |
} | |
public String getDescricao() { | |
return descricao; | |
} | |
public void setDescricao(String descricao) { | |
this.descricao = descricao; | |
} | |
public int getQtd() { | |
return qtd; | |
} | |
public void setQtd(int qtd) { | |
this.qtd = qtd; | |
} | |
} |
GsonExample.java (Main)
Agora vamos botar em prática tudo o que montamos até aqui, primeiro vou apresentar o código e vou comentando passo a passo ele.
/* | |
* Copyright (C) 2017 haynes | |
* | |
* This program is free software: you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation, either version 3 of the License, or | |
* (at your option) any later version. | |
* | |
* This program is distributed in the hope that it will be useful, | |
* but WITHOUT ANY WARRANTY; without even the implied warranty of | |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
* GNU General Public License for more details. | |
* | |
* You should have received a copy of the GNU General Public License | |
* along with this program. If not, see <http://www.gnu.org/licenses/>. | |
*/ | |
package gsonexample; | |
import gsonexample.cliente.Cliente; | |
import gsonexample.pedido.Pedido; | |
import gsonexample.pedido.itens.ItemPedido; | |
import com.google.gson.Gson; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.io.Reader; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
/** | |
* | |
* @author haynes | |
*/ | |
public class GsonExample { | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
/** | |
* Como escrever um arquivo JSON | |
*/ | |
createJSON(); | |
System.out.println("\n\n"); | |
/** | |
* Como ler arquivo json | |
*/ | |
try { | |
File filePath = new File("dist/pedido.json"); | |
loadJSON(filePath); | |
} catch (FileNotFoundException ex) { | |
Logger.getLogger(GsonExample.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
} | |
public static void createJSON() { | |
Pedido pedido = new Pedido(); | |
Cliente cliente = new Cliente(); | |
cliente.setId(12); | |
cliente.setNome("Guilherme Haynes"); | |
pedido.setId(1234); | |
pedido.setCliente(cliente); | |
for (int i = 1; i <= 3; i++) { | |
ItemPedido item = new ItemPedido(); | |
item.setId(i); | |
item.setDescricao("Item " + i); | |
item.setQtd(10); | |
pedido.getItens().add(item); | |
} | |
Gson gson = new Gson(); | |
String json = gson.toJson(pedido); | |
System.out.println(json); | |
} | |
public static void loadJSON(File filePath) throws FileNotFoundException { | |
Reader reader = new FileReader(filePath); | |
Gson gson = new Gson(); | |
Pedido pedido = gson.fromJson(reader, Pedido.class); | |
System.out.println("Pedido nº: " + pedido.getId()); | |
System.out.println("Cliente nº: " + pedido.getCliente().getId() + " | Nome: " + pedido.getCliente().getNome()); | |
System.out.println("Itens: "); | |
for (ItemPedido item : pedido.getItens()) { | |
System.out.println("----------------------------------------------------------"); | |
System.out.println(" Ped. nº: " + item.getId()); | |
System.out.println(" Item: " + item.getDescricao()); | |
System.out.println(" Qtd: " + item.getQtd()); | |
} | |
} | |
} |
No método createJSON() mostro como criar um JSON a partir de uma classe Java. No caso, o GSON analisa a estrutura da classe, e faz o JSON de acordo com a estrutura que foi passada como parâmetro do método toJson() que nos retorna uma string contendo o JSON.
Agora no método loadJson() recebo um arquivo (do tipo File) pelo parâmetro. Após isso eu crio um reader desse arquivo e passo como parâmetro para o método fromJson() do objeto gson. Junto, ele pede um outro parâmetro que é a Classe que representa esse JSON, no nosso caso é a classe Pedido.
Lembra que no começo da explicação eu disse que o nome das chaves do JSON tem que ser o mesmo dos nomes dos atributos da classe? Então, o método fromJson verifica se é igual. Se não for, ele retorna um erro de JsonSyntaxException, indicando que há campos incompatíveis com a classe especificada.
Finalizando
A biblioteca Gson é muito útil quando se quer trabalhar com uma API REST por exemplo, ou no desenvolvimento de Aplicativos Android, para poder enviar e consumir dados utilizando pouca rede.
Para quem quiser, aqui vai o projeto no github, para poder testar e ver melhor o código.
https://github.com/zerossB/GsonExample
Referências
https://pt.stackoverflow.com/a/4171/38938
http://www.aquiejava.com/2012/11/gson-converta-json-em-objeto-java-de-forma-simples.html