logo

Com analitzar JSON a Java

JSON (JavaScript Object Notation) és un format d'intercanvi de dades lleuger, basat en text i independent de l'idioma, fàcil de llegir i escriure per a persones i màquines. JSON pot representar dos tipus estructurats: objectes i matrius. Un objecte és una col·lecció no ordenada de zero o més parells nom/valor. Una matriu és una seqüència ordenada de zero o més valors. Els valors poden ser cadenes, números, booleans, nuls i aquests dos tipus estructurats.

A continuació es mostra un exemple senzill de la Viquipèdia que mostra la representació JSON d'un objecte que descriu una persona. L'objecte té valors de cadena per al nom i el cognom, un valor de nombre per a l'edat, un valor d'objecte que representa l'adreça de la persona i un valor de matriu d'objectes de número de telèfon.



 { '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' } ] }>

Processament JSON en Java: L'API de Java per al processament JSON JSON.simple és una simple biblioteca de Java que permet analitzar, generar, transformar i consultar JSON.

guineu o llop

Començant : Heu de descarregar el json-simple-1.1 jar i poseu-lo al vostre CLASSPATH abans de compilar i executar els codis d'exemple següents.

API Json-Simple: Proporciona models d'objectes per a estructures d'objectes i matrius JSON. Aquestes estructures JSON es representen com a models d'objectes mitjançant tipus JSONObject i JSONArray . JSONObject proporciona a Mapa vista per accedir a la col·lecció no ordenada de zero o més parells de nom/valor del model. De la mateixa manera, JSONArray proporciona a Llista vista per accedir a la seqüència ordenada de zero o més valors del model.



Escriu JSON en un fitxer

Vegem un exemple que escriu dades JSON a sobre en un fitxer JSONExample.json, amb l'ajuda de JSONObject i 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();> >}> }>

java públic vs privat

>

>

Sortida del fitxer 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 : A JSON, un objecte és un conjunt no ordenat de parells nom/valor, de manera que JSONObject no conserva l'ordre dels parells nom/valor d'un objecte, ja que (per definició) no és significatiu. Per tant, al nostre fitxer de sortida, l'ordre no es conserva.

Llegir JSON d'un fitxer

Vegem un exemple que llegeix dades JSON del fitxer creat anteriorment JSONExample.json amb l'ajuda de JSONParser, JSONObject i JSONArray.




// 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());> >}> >}> >}> }>

>

llocs com ara bedpage
>

Sortida:

 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>