JSON parser in JAVA (json.org)

JSON (JavaScript Object Notation) è un formato di scambio di dati piuttosto leggero (meno voluminoso di XML): è facilmente leggibile e scrivibile per le persone (oltre che per le macchine) ed è basato su un subset di JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON è caratterizzato da una doppia struttura:

In particolare, in un documento JSON:

Per il parsing di documenti JSON in JAVA si può usare la libreria org.json. L'oggetto di base è org.json.JSONObject, il cui costruttore ammette come parametro anche una stringa contenente il documento JSON.

E' possibile navigare la gerarchia del documento JSON facendo riferimento a tre tipologie di oggetti:

La seguente porzione di codice mostra come, a partire da un oggetto File, sia possibile navigare la gerarchia:


private void parse(File inputFile) {
 String allInputFile = this.readFile(fileToParse.getAbsolutePath(), 
 	StandardCharsets.UTF_8);
 JSONObject obj = new JSONObject(allInputFile);
 if(obj!=null){
  JSONArray dataset = obj.optJSONArray("dataset");
  if(dataset!=null){
   for(int i=0; i<dataset.length(); i++){
	JSONObject current = dataset.optJSONObject(i);
	
    //flat objects
    if(current.get("identifier")!=null)
     System.out.println(current.get("identifier").toString());
     //sub-objects
     JSONObject subObject;
     if(current.get("contactPoint")!=null) {
      subObject = obj.optJSONObject("contactPoint");
      if(subObject.get("fn")!=null)
       System.out.println(subObject.get("fn").toString());
     }		
    }
   }
  }
 }
}

private String readFile(String path, Charset encoding) 
	throws IOException 
{
 byte[] encoded = Files.readAllBytes(Paths.get(path));
 return new String(encoded, encoding);
}		

Come altro esempio di documento JSON, vediamo l'output di una chiamata alle Custom Search Google API:

	
{
 "kind": "customsearch#search",
 "searchInformation": {
  "searchTime": 0.15376,
  "formattedSearchTime": "0.15",
  "totalResults": "795",
  "formattedTotalResults": "795"
 },
 "items": [
  {
   "kind": "customsearch#result",
   "title": "Effect of Some Extrusion Variables on Rheological Properties",
   "link": "http://www.scielo.br/scielo.php?...",
   "displayLink": "www.scielo.br",
   "snippet": "An increase in feed rate decreased WAI and WSI, but...",
   "formattedUrl": "www.scielo.br/scielo.php?pid=S0104...",
   "pagemap": {
    "metatags": [
     {
      "citation_journal_title": "Brazilian Journal of Chemical Engineering",
      "citation_publisher": "Associação Brasileira de Engenharia Química",
      "citation_title": "Effect of Some Extrusion Variables on...",
      "citation_date": "12/1998",
      "citation_volume": "15",
      "citation_issue": "4",
      "citation_issn": "0104-6632",
      "citation_doi": "10.1590/S0104-66321998000400006",
      ""citation_pdf_url": 
      "http://www.scielo.br/scielo.php?script=sci_pdf...",
      "citation_author": "Chang, Y.K.",
      "citation_author_institution": "Universidade Estadual de Campinas",
      "citation_firstpage": "370",
      "citation_lastpage": "381",
      "citation_id": "10.1590/S0104-66321998000400006"
     }
    ]
   }
  },
  {
   ...
   }
  }
 ]
}}			

Il codice Java per estrarre alcune informazioni dal documento può essere:


GETHttpRequest req = new GETHttpRequest();
Map<String, String> header_map = new HashMap<String, String>();
String jsonStr = req.dereferenceURI(query, header_map);
JSONObject obj = new JSONObject(jsonStr);
if(obj!=null){
	JSONArray items = obj.optJSONArray("items");
	if(items!=null){
		for(int i=0; i<items.length(); i++){
			JSONObject current = items.optJSONObject(i);
			GoogleObject tmp = new GoogleObject();
			tmp.setTitle(current.optString("title"));
			tmp.setSnippet(current.optString("htmlSnippet"));
			tmp.setPage(current.optString("link"));	
			this.googleobjs.add(tmp);
		}
	}
}