tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 JSON > GOOGLE GSON > Generic Types

Generic Types 

Google-gson is a java library from Google for encoding and decoding JSON text. Get the latest binaries from http://code.google.com/p/google-gson/. The following example shows serializing and de-serializing generic types.

File Name  :  
com/bethecoder/tutorials/google_gson/tests/GenericTypes.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.google_gson.tests;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

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

public class GenericTypes {

  /**
   @param args
   */
  public static void main(String[] args) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    List<String> strings = Arrays.asList("ONE""TWO""THREE""FOUR");
    String jsonStr = gson.toJson(strings);
    System.out.println(jsonStr)//We loose the type info once we serialize to JSON string
  
    //Specify the explicit type for de-serialization
    Type listType = new TypeToken<List<String>>() {}.getType();
    strings = gson.fromJson(jsonStr, listType);
    System.out.println(strings);
  }

}
   

It gives the following output,
[
  "ONE",
  "TWO",
  "THREE",
  "FOUR"
]

[ONE, TWO, THREE, FOUR]



 
  


  
bl  br