Monday, September 16, 2013

Convert Java Object From JSON (Gson API)



  In this article, we show you an example of how to use Gson, JSON library, to convert json to object. Gson API is easy to learn and implement, what we need to know are the following two methods:


  •  toJson() – Convert Java object to JSON format 
  •  fromJson() – Convert JSON into Java object 


 We suppose that an http Get request is made to Google search engine. The response from google is in json format and a part of this response is presented here:
 
 .
 .
 .
"items": [
  {
   "kind": "customsearch#result",
   "title": "Formation of the First Stars",
   "htmlTitle": "Formation of the First \u003cb\",
   "link": "http://arxiv.org/abs/1305.5178",
   "displayLink": "arxiv.org",
   "snippet": "May 22, 2013 ... Abstract: Understanding the formation of ...",
   "htmlSnippet": "May 22, 2013 \u003cb\u003e...",
   "cacheId": "CbjG-txlc30J",
   "formattedUrl": "arxiv.org/abs/1305.5178",
   "htmlFormattedUrl": "arxiv.org/abs/1305.5178",
   "pagemap": {
    "metatags": [
     {
      "citation_title": "Formation of the First Stars",
      "citation_author": "Bromm, Volker",
      "citation_date": "2013/05/22",
      "citation_online_date": "2013/05/22",
      "citation_pdf_url": "http://arxiv.org/pdf/1305.5178",
      "citation_arxiv_id": "1305.5178"
     }
    ]
   }
  },
  {
   "kind": "customsearch#result",
   "title": "Fast radio bursts: the last sign of supramassive neutron stars",
   "htmlTitle": "Fast radio bursts: the last sign of supramassive neutron",
   "link": "http://arxiv.org/abs/1307.1409",
   "displayLink": "arxiv.org",
   "snippet": "Jul 4, 2013 ... Abstract: Several fast radio bursts , ...",
   "htmlSnippet": "Jul 4, 2013 \u003cb\u003e...\u003c/b\u003e Abstract:....",
   "cacheId": "kcClCUGrI9IJ",
   "formattedUrl": "arxiv.org/abs/1307.1409",
   "htmlFormattedUrl": "arxiv.org/abs/1307.1409",
   "pagemap": {
    "metatags": [
     {
      "citation_title": "Fast radio bursts: the last sign of supramassive..",
      "citation_author": "Falcke, Heino",
      "citation_date": "2013/07/04",
      "citation_online_date": "2013/07/04",
      "citation_pdf_url": "http://arxiv.org/pdf/1307.1409",
      "citation_arxiv_id": "1307.1409"
     }
    ]
   }
  },……]
 .
 .
 .
Generally the response data includes three main classes of properties:

 • Search metadata
 • Custom search engine metadata
 • Search results

 As shown in the sample output above The items array contains the actual search results. The search results include the URL, title and text snippets that describe the result.
*In addition, they can contain pagemap information, if applicable. The metatags array contains the available metadata that come with the search result. A sample of metadata is given as an example below:

JSON METATAGS SAMPLE
             

      .
      .
   citation_language
   prism.publicationname: "Icarus"
   prism.issn: "0019-1035"
   prism.volume: "216"
   prism.startingpage: "136"
   prism.endingpage: "140"
   dc.language: "en"
   dc.identifier: "doi:10.1016/j.icarus.2011.08.022"
   dc.date: "2011-11"
   dc.source: "Icarus, Volume 216, Issue 1, p. 136-140."
   eprints.creators_name: "Barnes, Jason W."
   eprints.creators_id: "Barnes-J-W"
   eprints.type: "article"
   eprints.datestamp: "2011-12-19 19:04:30"
   eprints.lastmod: "2011-12-19 19:04:30"
   eprints.metadata_visibility: "show"
   eprints.title: "Organic sedimentary deposits in Titan’s dry lakebeds: Probable evaporite"
   eprints.ispublished: "pub"
   eprints.full_text_status: "none"
   eprints.keywords: "Titan"
   eprints.date: "2011-11"
   eprints.date_type: "published"
   eprints.publication: "Icarus"
   eprints.volume: "216"
   eprints.number: "1"
   eprints.publisher: "Elsevier"
     .
     .
  
JAVA CLASS:

  The java class reads data from response.json ,then “maps” them back to a java object and displays it.                                                                                                                       *Note:Dependencies are omitted
 
public class CustomSearch {
 
 static private String title= new String();
 static private String htmlTitle= new String();
 static private String link= new String();
 static private String formattedUrl= new String();
 static private String htmlFormattedUrl= new String();
 static private List metatagList= new ArrayList();
 

 
 public static void main(String[] args) throws IOException
 {
    
     File jsonFile = new File("C:\\..\\response.json");
     Gson gson = new Gson();
     Response response = gson.fromJson(new FileReader(jsonFile), Response.class);
 
     for (Item item : response.items)
     {      
       System.out.println("[DEBUG] title: " + item.title);
       System.out.println("[DEBUG] htmlTitle: " + item.htmlTitle);
       System.out.println("[DEBUG] link: " + item.link);
       System.out.println("[DEBUG] formattedUrl: " + item.formattedUrl);
       System.out.println("[DEBUG] htmlFormattedUrl: " + item.htmlFormattedUrl);
     
       // Assign values
       title = item.title;
       htmlTitle = item.htmlTitle;
       link = item.link;
       formattedUrl = item.formattedUrl;
       htmlFormattedUrl = item.htmlFormattedUrl;
 
       Pagemap pagemap = item.pagemap;
       Iterator iterMetatags ;
     
       if(pagemap != null)
       {
        iterMetatags = pagemap.metatags.listIterator();
     
        while(iterMetatags.hasNext())
        {
         Metatag element = iterMetatags.next();

         System.out.println("[DEBUG] Metatag citation_doi :" + element.citation_doi);
         System.out.println("[DEBUG] Metatag citation_arxiv_id :" + element.citation_arxiv_id);
         System.out.println("[DEBUG] Metatag citation_author :" + element.citation_author);
         System.out.println("[DEBUG] Metatag citation_date :" + element.citation_date);
         System.out.println("[DEBUG] Metatag citation_title :" + element.citation_title);
         System.out.println("[DEBUG] Metatag citation_pdf_url :" + element.citation_pdf_url);
       
         System.out.println("[DEBUG] Metatag title :" + element.title);
         System.out.println("[DEBUG] Metatag creator :" + element.creator);
         System.out.println("[DEBUG] Metatag creationdate :" + element.creationdate);
         System.out.println("[DEBUG] Metatag moddate :" + element.moddate);
         System.out.println("[DEBUG] Metatag producer :" + element.producer);
         System.out.println("[DEBUG] Metatag company :" + element.company);
       
         System.out.println("[DEBUG] Metatag dc_title :" + element.dc_title);
         System.out.println("[DEBUG] Metatag dc_description :" + element.dc_description);
         System.out.println("[DEBUG] Metatag dc_creator :" + element.dc_creator)    
       
         /* Add metadata values */
         metatagList.add(element.citation_doi);
         metatagList.add(element.citation_arxiv_id);
         metatagList.add(element.citation_author);
         metatagList.add(element.citation_date);
         metatagList.add(element.citation_title);
         metatagList.add(element.citation_pdf_url);
       
         metatagList.add(element.title);
         metatagList.add(element.creator);
         metatagList.add(element.creationdate);
         metatagList.add(element.moddate);
         metatagList.add(element.producer);
         metatagList.add(element.company);
       
         metatagList.add(element.dc_title);
         metatagList.add(element.dc_description);
         metatagList.add(element.dc_creator);
        }     
     
       }
     
     
     }

 
 }
 
 //Mapping Json response to Java Object  
 
 class Response
 {
  List items;
 }
 
 class Item
 {
  String title;
  String htmlTitle;
  String link;
  String formattedUrl;
  String htmlFormattedUrl;
  Pagemap pagemap;
 }
 class Pagemap
 {
  List metatags;
 }
 class Metatag
 {
  String citation_doi;
  String citation_title;
  String citation_author;
  String citation_date;
  String citation_pdf_url;
  String citation_arxiv_id;
  
  String title;
  String creator;
  String creationdate;
  String moddate;
  String producer;
  String company;
  
  @SerializedName("dc.title")
  String dc_title;
  @SerializedName("dc.description")
  String dc_description;
  @SerializedName("dc.creator")
  String dc_creator;
  
 }
 
}
Note that the annotation @SerializedName() is a field renaming technique that it is used to rename field names which are not java compatible.(e.g.:dc.creator)

1 comment: