JSON (JavaScript Object Notation) este un format de schimb de date ușor, bazat pe text, independent de limbă, care este ușor de citit și scris pentru oameni și mașini. JSON poate reprezenta două tipuri structurate: obiecte și matrice. Un obiect este o colecție neordonată de zero sau mai multe perechi nume/valoare. O matrice este o secvență ordonată de zero sau mai multe valori. Valorile pot fi șiruri, numere, booleeni, nul și aceste două tipuri structurate.
Mai jos este un exemplu simplu din Wikipedia care arată reprezentarea JSON a unui obiect care descrie o persoană. Obiectul are valori de șir pentru prenume și nume, o valoare numerică pentru vârstă, o valoare de obiect care reprezintă adresa persoanei și o valoare de matrice a obiectelor numere de telefon.
{ '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' } ] }> Procesare JSON în Java: API-ul Java pentru procesarea JSON JSON.simplu este o bibliotecă Java simplă care permite analizarea, generarea, transformarea și interogarea JSON.
Noțiuni de bază : Trebuie să descărcați json-simple-1.1 jar și puneți-l în CLASSPATH înainte de a compila și a rula exemplele de coduri de mai jos.
- Pentru importarea jar în IDE, cum ar fi Eclipse, consultați Aici .
- Dacă utilizați Maven, puteți utiliza următorul link Maven https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1
API Json-Simple: Oferă modele de obiecte pentru obiecte JSON și structuri de matrice. Aceste structuri JSON sunt reprezentate ca modele de obiecte folosind tipuri JSONObject și JSONArray . JSONObject oferă a Hartă vizualizare pentru a accesa colecția neordonată de zero sau mai multe perechi nume/valoare din model. În mod similar, JSONArray oferă o Listă vizualizare pentru a accesa secvența ordonată de zero sau mai multe valori din model.
livecricket.este
Scrieți JSON într-un fișier
Să vedem un exemplu care scrie mai sus date JSON într-un fișier JSONExample.json, cu ajutorul JSONObject și JSONArray.
powershell vs bash
// 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();> >}> }> |
>
>
șir în format java
Ieșire din fișierul 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' }> Notă : În JSON, un obiect este un set neordonat de perechi nume/valoare, deci JSONObject nu păstrează ordinea perechilor nume/valoare ale unui obiect, deoarece nu este (prin definiție) semnificativ. Prin urmare, în fișierul nostru de ieșire, ordinea nu este păstrată.
Citiți JSON dintr-un fișier
Să vedem un exemplu care citește datele JSON din fișierul creat de mai sus JSONExample.json cu ajutorul JSONParser, JSONObject și JSONArray.
np.sum
// 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());> >}> >}> >}> }> |
matrice java dinamică
>
>
Ieșire:
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>