Skip to content

Instantly share code, notes, and snippets.

@nedseb

nedseb/gson.md Secret

Last active December 15, 2015 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nedseb/29b8ca20dd0a5c14a9f3 to your computer and use it in GitHub Desktop.
Save nedseb/29b8ca20dd0a5c14a9f3 to your computer and use it in GitHub Desktop.
Exemples d'utilisation de la bibliothèque Gson

#Tutoriel Gson JSON (JavaScript Object Notation) est un format léger d'échange de données. Bien qu'originaire du monde du web, ces dernières années, ce format a été adopté par un nombre croissant d'applications Java comme un remplaçant d'XML. Comme son nom l'indique, ce format provient à la base de la manière de définir les objets en JavaScript. Il permet de représenter de l'information structurée. Une application utilisant ce format aura besoin de sérialiser ses objets en se format pour éventuellement les désérialiser plus tard.

Nous allons voir ici comment utiliser la bibliothèque Gson (http://code.google.com/p/google-gson/) pour convertir des objets depuis/vers le format JSON.

Gson est relativement simple à maitriser car pour le travail que nous avons à faire, il y a seulement les deux méthodes suivante à connaitre :

  • toJson() : Convertie un objet Java en sa représentation au format JSON.
  • fromJson() : Convertie une description JSON en un objet Java.

##Installation La bibliothèque Gson est directement présente dans les dépôts Maven. Pour l'ajouter à votre projet, il vous suffit d'ajouter les lignes suivantes dans la section <dependencies> du fichier pom.xml :

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.2.2</version>
</dependency>

##POJO Pour faire sa sérialisation/désérialisation, Gson se base sur des objets Java standards (des POJO). En supposant que l'on veuille par la suite désérialiser la chaine JSON suivante :

{
    "numéro": "001",
    "nom": "Bulbizarre",
    "espece": "Graine",
    "taille": "0.7",
    "poids": "6.9",
    "fmratio": ".125",
    "oeufpas": "5120",
    "effortval": "+1Att.Spé",
    "type1": "Plante",
    "type2": "Poison",
    "expval": "64",
    "expmax": "1059860",
    "captureval": "45",
    "capspe1": "Engrais",
    "capspe2": "Chlorophyle",
    "couleur": "Vert",
    "forme": "8",
    "attaques": [
        {
            "niveau": "Départ",
            "nom": "Charge",
            "puissance": "35",
            "precision": "95",
            "pp": "35"
        },
        {
            "niveau": "Départ",
            "nom": "Rugissement",
            "puissance": "-",
            "precision": "100",
            "pp": "40"
        },
        {
            "niveau": "N.7",
            "nom": "Vampigraine",
            "puissance": "-",
            "precision": "90",
            "pp": "10"
        },
        {
            "niveau": "N.13",
            "nom": "Fouet Lianes",
            "puissance": "35",
            "precision": "100",
            "pp": "10"
        }
    ]
}

Nous devons pour y arriver, définir les classes DataObjectPokemon et DataObjectAttack pour représenter les deux types d'objets présent dans cette chaîne.

public class DataObjectAttack {
    String niveau;
    String nom;
    String puissance;
    String precision;
    String pp;

    public DataObjectAttack(String niveau, String nom, String puissance, String precision, 
                            String pp) {
        this.niveau = niveau;
        this.nom = nom;
        this.puissance = puissance;
        this.precision = precision;
        this.pp = pp;
    }

    @Override
    public String toString() {
        return "DataObjectAttack{" +
                "niveau='" + niveau + '\'' +
                ", nom='" + nom + '\'' +
                ", puissance=" + puissance +
                ", precision=" + precision +
                ", pp=" + pp +
                '}';
    }
}
public class DataObjectPokemon {
    String nom;
    String espece;
    float taille;
    float poids;
    float fmratio;
    String effortval;
    String type1;
    String type2;
    int expval;
    int expmax;
    int captureval;
    String capspe1;
    String capspe2;
    String couleur;
    int forme;

    DataObjectAttack[] attaques;

    public DataObjectPokemon(){
    }

    public DataObjectPokemon(String nom, String espece, float taille, float poids, 
                             float fmratio, String effortval,
                             String type1, String type2, int expval, int expmax, 
                             int captureval, String capspe1,
                             String capspe2, String couleur, int forme, 
                             DataObjectAttack[] attaques) {
        this.nom = nom;
        this.espece = espece;
        this.taille = taille;
        this.poids = poids;
        this.fmratio = fmratio;
        this.effortval = effortval;
        this.type1 = type1;
        this.type2 = type2;
        this.expval = expval;
        this.expmax = expmax;
        this.captureval = captureval;
        this.capspe1 = capspe1;
        this.capspe2 = capspe2;
        this.couleur = couleur;
        this.forme = forme;
        this.attaques = attaques;
    }

    @Override
    public String toString() {
        return "DataObjectPokemon{" +
                "nom='" + nom + '\'' +
                ", espece='" + espece + '\'' +
                ", taille=" + taille +
                ", poids=" + poids +
                ", fmratio=" + fmratio +
                ", effortval='" + effortval + '\'' +
                ", type1='" + type1 + '\'' +
                ", type2='" + type2 + '\'' +
                ", expval=" + expval +
                ", expmax=" + expmax +
                ", captureval=" + captureval +
                ", capspe1='" + capspe1 + '\'' +
                ", capspe2='" + capspe2 + '\'' +
                ", couleur='" + couleur + '\'' +
                ", forme=" + forme +
                ", attaques=" + (attaques == null ? null : Arrays.asList(attaques)) +
                '}';
    }
}

##Exemple d'utilisation de fromJson() Le code suivant converti la chaîne JSON données en exemple en supposant qu'elle est située dans le fichier src/main/resources/pokemon.json. Pour faire la correspondance entre le JSON et le POJO, Gson suppose que par défaut, les données membre ont même nom et même type dans les deux formats.

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class App 
{
    public static void main( String[] args ) {
        Gson gson = new Gson();

        BufferedReader br = new BufferedReader(
                               new InputStreamReader(App.class.getClassLoader().getResourceAsStream("pokemon.json")));

        //convert the json string back to object
        DataObjectPokemon obj = gson.fromJson(br, DataObjectPokemon.class);

        System.out.println(obj);
    }
}

Pour charger un tableau d'objet DataObjectPokemon situé dans le fichier src/main/resources/pokedex.json, seul l'appel à la méthode fromJson() a été modifié.

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class App 
{
    public static void main( String[] args ){
        Gson gson = new Gson();

        BufferedReader br = new BufferedReader(
                              new InputStreamReader(App.class.getClassLoader().getResourceAsStream("pokedex.json")));
        //convert the json string back to object
        DataObjectPokemon[] obj = gson.fromJson(br, DataObjectPokemon[].class);

        System.out.println(Arrays.toString(obj));
    }
}

##Exemple d'utilisation de toJson() La seconde méthode est encore plus simple à utiliser. Voici un exemple d'utilisation :

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class App 
{
    public static void main( String[] args ){
        Gson gson = new Gson();
        DataObjectPokemon obj = new DataObjectPokemon();
        String json = gson.toJson(obj)
        System.out.println(obj);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment