Gson - Contoh Serialisasi

Pada bab ini, kita akan membahas serialisasi / deserialisasi array, koleksi, dan generik.

Contoh Array

int[] marks = {100,90,85}; 
//Serialization 
System.out.println("marks:" + gson.toJson(marks));        

//De-serialization 
marks = gson.fromJson("[100,90,85]", int[].class); 
System.out.println("marks:" + Arrays.toString(marks));

Contoh

Mari kita lihat Array serialization / de-serialization beraksi. Buat file kelas Java bernamaGsonTester di C: \> GSON_WORKSPACE.

File − GsonTester.java

import java.util.Arrays; 
import com.google.gson.Gson;  

public class GsonTester { 
   public static void main(String args[]) { 
   
      Gson gson = new Gson(); 
      int[] marks = {100,90,85}; 
      String[] names = {"Ram","Shyam","Mohan"}; 
      
      //Serialization 
      System.out.print("{"); 
      System.out.print("marks:" + gson.toJson(marks) + ",");       
      System.out.print("names:" + gson.toJson(names));       
      System.out.println("}");  
      
      //De-serialization 
      marks = gson.fromJson("[100,90,85]", int[].class); 
      names = gson.fromJson("[\"Ram\",\"Shyam\",\"Mohan\"]", String[].class);
      System.out.println("marks:" + Arrays.toString(marks)); 
      System.out.println("names:" + Arrays.toString(names));     
   }      
}

Verifikasi hasilnya

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

C:\GSON_WORKSPACE>javac GsonTester.java

Sekarang jalankan GsonTester untuk melihat hasilnya -

C:\GSON_WORKSPACE>java GsonTester

Verifikasi hasilnya.

{marks:[100,90,85],names:["Ram","Shyam","Mohan"]} 
marks:[100, 90, 85] 
names:[Ram, Shyam, Mohan]

Contoh Koleksi

List marks = new ArrayList(); 
//Serialization 
System.out.println("marks:" + gson.toJson(marks));        

//De-serialization 
//get the type of the collection. 
Type listType = new TypeToken<list>(){}.getType(); 

//pass the type of collection 
marks = gson.fromJson("[100,90,85]", listType); 
System.out.println("marks:" +marks);</list>

Contoh

Mari kita lihat Serialization / de-serialization koleksi beraksi. Buat file kelas Java bernamaGsonTester di C: \> GSON_WORKSPACE.

File − GsonTester.java

import java.lang.reflect.Type; 
import java.util.ArrayList; 
import java.util.Collection;  

import com.google.gson.Gson; 
import com.google.gson.reflect.TypeToken;  

public class GsonTester { 
   public static void main(String args[]) { 
   
      Gson gson = new Gson(); 
      Collection<Integer> marks = new ArrayList<Integer>();  
      marks.add(100); 
      marks.add(90); 
      marks.add(85);  
      
      //Serialization 
      System.out.print("{"); 
      System.out.print("marks:" + gson.toJson(marks));             
      System.out.println("}");  
      
      //De-serialization 
      Type listType = new TypeToken<Collection<Integer>>(){}.getType(); 
      marks = gson.fromJson("[100,90,85]", listType); 
      System.out.println("marks:" +marks);     
   }      
}

Verifikasi hasilnya

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

C:\GSON_WORKSPACE>javac GsonTester.java

Sekarang jalankan GsonTester untuk melihat hasilnya -

C:\GSON_WORKSPACE>java GsonTester

Verifikasi hasilnya.

{marks:[100,90,85]} 
marks:[100, 90, 85]

Contoh Generik

Gson menggunakan API refleksi Java untuk mendapatkan tipe objek yang akan dipetakan teks Json. Tetapi dengan obat generik, informasi ini hilang selama serialisasi. Untuk mengatasi masalah ini, Gson menyediakan kelascom.google.gson.reflect.TypeToken untuk menyimpan jenis objek generik.

Contoh

Mari kita lihat serialisasi / de-serialisasi Generik beraksi. Buat file kelas Java bernamaGsonTester di C: \> GSON_WORKSPACE.

File − GsonTester.java

import java.lang.reflect.Type; 

import com.google.gson.Gson; 
import com.google.gson.reflect.TypeToken;  

public class GsonTester { 
   public static void main(String args[]) { 
   
      // create a shape class of type circle. 
      Shape<Circle> shape = new Shape<Circle>();  
      
      // Create a Circle object 
      Circle circle = new Circle(5.0);  
      
      //assign circle to shape 
      shape.setShape(circle);  
      Gson gson = new Gson(); 
      
      // Define a Type shapeType of type circle. 
      Type shapeType = new TypeToken<Shape<Circle>>() {}.getType();  
      
      //Serialize the json as ShapeType 
      String jsonString = gson.toJson(shape, shapeType); 
      System.out.println(jsonString);  
      Shape shape1 = gson.fromJson(jsonString, Shape.class); 
      
      System.out.println(shape1.get().getClass()); 
      System.out.println(shape1.get().toString()); 
      System.out.println(shape1.getArea());  
      Shape shape2 = gson.fromJson(jsonString, shapeType); 
      System.out.println(shape2.get().getClass()); 
      System.out.println(shape2.get().toString()); 
      System.out.println(shape2.getArea()); 
   }      
}  

class Shape <T> { 
   public T shape;  
   
   public void setShape(T shape) { 
      this.shape = shape; 
   }  
   public T get() { 
      return shape; 
   }  
   public double getArea() { 
      if(shape instanceof Circle) { 
         return ((Circle) shape).getArea(); 
      } else { 
         return 0.0; 
      } 
   } 
}  

class Circle { 
   private double radius;  
   
   public Circle(double radius){ 
      this.radius = radius; 
   }  
   public String toString() { 
      return "Circle"; 
   }  
   public double getRadius() { 
      return radius; 
   }  
   public void setRadius(double radius) { 
      this.radius = radius; 
   }  
   public double getArea() { 
      return (radius*radius*3.14); 
   } 
}

Verifikasi hasilnya

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

C:\GSON_WORKSPACE>javac GsonTester.java

Sekarang jalankan GsonTester untuk melihat hasilnya -

C:\GSON_WORKSPACE>java GsonTester

Verifikasi hasilnya.

{"shape":{"radius":5.0}} 
class com.google.gson.internal.LinkedTreeMap 
{radius = 5.0} 
0.0 
class Circle 
Circle 
78.5