logo

Come analizzare JSON in Java

JSON (JavaScript Object Notation) è un formato di scambio dati leggero, basato su testo e indipendente dalla lingua, facile da leggere e scrivere da parte di esseri umani e macchine. JSON può rappresentare due tipi strutturati: oggetti e array. Un oggetto è una raccolta non ordinata di zero o più coppie nome/valore. Un array è una sequenza ordinata di zero o più valori. I valori possono essere stringhe, numeri, booleani, null e questi due tipi strutturati.

impostato in Java

Di seguito è riportato un semplice esempio tratto da Wikipedia che mostra la rappresentazione JSON di un oggetto che descrive una persona. L'oggetto ha valori stringa per nome e cognome, un valore numerico per l'età, un valore oggetto che rappresenta l'indirizzo della persona e un valore array di oggetti numero di telefono.

 { 'firstName': 'John', 'lastName': 'Smith', 'age': 25, 'address': { 'streetAddress': '21 2nd Street', 'city': 'New York', 'state': 'NY', 'postalCode': 10021 }, 'phoneNumbers': [ { 'type': 'home', 'number': '212 555-1234' }, { 'type': 'fax', 'number': '646 555-4567' } ] }>

Elaborazione JSON in Java: L'API Java per l'elaborazione JSON JSON.semplice è una semplice libreria Java che consente di analizzare, generare, trasformare ed eseguire query su JSON.



Iniziare : È necessario scaricare il file vaso json-simple-1.1 e inseriscilo nel tuo CLASSPATH prima di compilare ed eseguire i codici di esempio seguenti.

API Json-Simple: Fornisce modelli di oggetti per oggetti JSON e strutture di array. Queste strutture JSON sono rappresentate come modelli a oggetti utilizzando i tipi JSONObject E JSONArray . JSONObject fornisce a Carta geografica view per accedere alla raccolta non ordinata di zero o più coppie nome/valore dal modello. Allo stesso modo, JSONArray fornisce a Elenco view per accedere alla sequenza ordinata di zero o più valori dal modello.

Scrivi JSON in un file

Vediamo un esempio che scrive i dati JSON sopra in un file JSONExample.json, con l'aiuto di JSONObject e JSONArray.




// Java program for write JSON to a file> > import> java.io.FileNotFoundException;> import> java.io.PrintWriter;> import> java.util.LinkedHashMap;> import> java.util.Map;> import> org.json.simple.JSONArray;> import> org.json.simple.JSONObject;> > public> class> JSONWriteExample> {> >public> static> void> main(String[] args)>throws> FileNotFoundException> >{> >// creating JSONObject> >JSONObject jo =>new> JSONObject();> > >// putting data to JSONObject> >jo.put(>'firstName'>,>'John'>);> >jo.put(>'lastName'>,>'Smith'>);> >jo.put(>'age'>,>25>);> > >// for address data, first create LinkedHashMap> >Map m =>new> LinkedHashMap(>4>);> >m.put(>'streetAddress'>,>'21 2nd Street'>);> >m.put(>'city'>,>'New York'>);> >m.put(>'state'>,>'NY'>);> >m.put(>'postalCode'>,>10021>);> > >// putting address to JSONObject> >jo.put(>'address'>, m);> > >// for phone numbers, first create JSONArray> >JSONArray ja =>new> JSONArray();> > >m =>new> LinkedHashMap(>2>);> >m.put(>'type'>,>'home'>);> >m.put(>'number'>,>'212 555-1234'>);> > >// adding map to list> >ja.add(m);> > >m =>new> LinkedHashMap(>2>);> >m.put(>'type'>,>'fax'>);> >m.put(>'number'>,>'212 555-1234'>);> > >// adding map to list> >ja.add(m);> > >// putting phoneNumbers to JSONObject> >jo.put(>'phoneNumbers'>, ja);> > >// writing JSON to file:'JSONExample.json' in cwd> >PrintWriter pw =>new> PrintWriter(>'JSONExample.json'>);> >pw.write(jo.toJSONString());> > >pw.flush();> >pw.close();> >}> }>

>

>

Output dal file JSONExample.json:

 { 'lastName':'Smith', 'address':{ 'streetAddress':'21 2nd Street', 'city':'New York', 'state':'NY', 'postalCode':10021 }, 'age':25, 'phoneNumbers':[ { 'type':'home', 'number':'212 555-1234' }, { 'type':'fax', 'number':'212 555-1234' } ], 'firstName':'John' }>

Nota : In JSON, un oggetto è un insieme non ordinato di coppie nome/valore, quindi JSONObject non preserva l'ordine delle coppie nome/valore di un oggetto, poiché (per definizione) non è significativo. Pertanto nel nostro file di output l'ordine non viene preservato.

Leggi JSON da un file

Vediamo un esempio che legge i dati JSON dal file JSONExample.json creato sopra con l'aiuto di JSONParser, JSONObject e JSONArray.

svuota la cache npm




// Java program to read JSON from a file> > import> java.io.FileReader;> import> java.util.Iterator;> import> java.util.Map;> > import> org.json.simple.JSONArray;> import> org.json.simple.JSONObject;> import> org.json.simple.parser.*;> > public> class> JSONReadExample> {> >public> static> void> main(String[] args)>throws> Exception> >{> >// parsing file 'JSONExample.json'> >Object obj =>new> JSONParser().parse(>new> FileReader(>'JSONExample.json'>));> > >// typecasting obj to JSONObject> >JSONObject jo = (JSONObject) obj;> > >// getting firstName and lastName> >String firstName = (String) jo.get(>'firstName'>);> >String lastName = (String) jo.get(>'lastName'>);> > >System.out.println(firstName);> >System.out.println(lastName);> > >// getting age> >long> age = (>long>) jo.get(>'age'>);> >System.out.println(age);> > >// getting address> >Map address = ((Map)jo.get(>'address'>));> > >// iterating address Map> >Iterator itr1 = address.entrySet().iterator();> >while> (itr1.hasNext()) {> >Map.Entry pair = itr1.next();> >System.out.println(pair.getKey() +>' : '> + pair.getValue());> >}> > >// getting phoneNumbers> >JSONArray ja = (JSONArray) jo.get(>'phoneNumbers'>);> > >// iterating phoneNumbers> >Iterator itr2 = ja.iterator();> > >while> (itr2.hasNext())> >{> >itr1 = ((Map) itr2.next()).entrySet().iterator();> >while> (itr1.hasNext()) {> >Map.Entry pair = itr1.next();> >System.out.println(pair.getKey() +>' : '> + pair.getValue());> >}> >}> >}> }>

>

>

Produzione:

 John Smith 25 streetAddress : 21 2nd Street postalCode : 10021 state : NY city : New York number : 212 555-1234 type : home number : 212 555-1234 type : fax>