Ciao ragazzi
In giro si trova davvero poco riguardo il parsing dei Json e dato che ho avuto la necessità di utilizzare questi metodi, ritengo opportuno condividere con voi questi frammenti di codice
Necessario:
Libreria Gson: https://code.google.com/p/google-gson/
Importate la libreria nel progetto di eclipse (io non uso AndroidStudio ma suppongo esista un repository su maven per Gson)
Procuratevi un Json (file sul dispositivo o tramite inputstream da Url)
Qui un esempio di Json:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
{ "text": "RT @PostGradProblem: In preparation for the NFL lockout, I will be spending twice as much time analyzing my fantasy baseball team during ...", "truncated": true, "in_reply_to_user_id": null, "in_reply_to_status_id": null, "favorited": false, "source": "<a href=\"http://twitter.com/\" rel=\"nofollow\">Twitter for iPhone</a>", "in_reply_to_screen_name": null, "in_reply_to_status_id_str": null, "id_str": "54691802283900928", "entities": { "user_mentions": [ { "indices": [ 3, 19 ], "screen_name": "PostGradProblem", "id_str": "271572434", "name": "PostGradProblems", "id": 271572434 } ], "urls": [ ], "hashtags": [ ] }, "contributors": null, "retweeted": false, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 4, "created_at": "Sun Apr 03 23:48:36 +0000 2011", "retweeted_status": { "text": "In preparation for the NFL lockout, I will be spending twice as much time analyzing my fantasy baseball team during company time. #PGP", "truncated": false, "in_reply_to_user_id": null, "in_reply_to_status_id": null, "favorited": false, "source": "<a href=\"http://www.hootsuite.com\" rel=\"nofollow\">HootSuite</a>", "in_reply_to_screen_name": null, "in_reply_to_status_id_str": null, "id_str": "54640519019642881", "entities": { "user_mentions": [ ], "urls": [ ], "hashtags": [ { "text": "PGP", "indices": [ 130, 134 ] } ] }, "contributors": null, "retweeted": false, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 4, "created_at": "Sun Apr 03 20:24:49 +0000 2011", "user": { "notifications": null, "profile_use_background_image": true, "statuses_count": 31, "profile_background_color": "C0DEED", "followers_count": 3066, "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", "listed_count": 6, "profile_background_image_url": "http://a3.twimg.com/a/1301071706/images/themes/theme1/bg.png", "description": "", "screen_name": "PostGradProblem", "default_profile": true, "verified": false, "time_zone": null, "profile_text_color": "333333", "is_translator": false, "profile_sidebar_fill_color": "DDEEF6", "location": "", "id_str": "271572434", "default_profile_image": false, "profile_background_tile": false, "lang": "en", "friends_count": 21, "protected": false, "favourites_count": 0, "created_at": "Thu Mar 24 19:45:44 +0000 2011", "profile_link_color": "0084B4", "name": "PostGradProblems", "show_all_inline_media": false, "follow_request_sent": null, "geo_enabled": false, "profile_sidebar_border_color": "C0DEED", "url": null, "id": 271572434, "contributors_enabled": false, "following": null, "utc_offset": null }, "id": 54640519019642880, "coordinates": null, "geo": null }, "user": { "notifications": null, "profile_use_background_image": true, "statuses_count": 351, "profile_background_color": "C0DEED", "followers_count": 48, "profile_image_url": "http://a1.twimg.com/profile_images/455128973/gCsVUnofNqqyd6tdOGevROvko1_500_normal.jpg", "listed_count": 0, "profile_background_image_url": "http://a3.twimg.com/a/1300479984/images/themes/theme1/bg.png", "description": "watcha doin in my waters?", "screen_name": "OldGREG85", "default_profile": true, "verified": false, "time_zone": "Hawaii", "profile_text_color": "333333", "is_translator": false, "profile_sidebar_fill_color": "DDEEF6", "location": "Texas", "id_str": "80177619", "default_profile_image": false, "profile_background_tile": false, "lang": "en", "friends_count": 81, "protected": false, "favourites_count": 0, "created_at": "Tue Oct 06 01:13:17 +0000 2009", "profile_link_color": "0084B4", "name": "GG", "show_all_inline_media": false, "follow_request_sent": null, "geo_enabled": false, "profile_sidebar_border_color": "C0DEED", "url": null, "id": 80177619, "contributors_enabled": false, "following": null, "utc_offset": -36000 }, "id": 54691802283900930, "coordinates": null, "geo": null }
Prima di iniziare il parsing è importante anche stabilire quali oggetti sono presenti all'interno del file (JsonObject o JsonArray). Esiste un comodissimo tool online che categorizza il contenuto del Json: Json Parser Online
Incollate il codice e nelle opzioni in alto a destra selezionate "Show JS Types", otterrete qualcosa di questo tipo:
Ora entra in gioco Gson. Questa libreria infatti, permette il parsing dell'intero Json, semplicemente fornendogli una classe java appositamente creata a patto che il contenuto della classe rifletta il contenuto del Json.
Un semplice esempio basato su questo file (riporto solo una parte):
MyJsonObject.java
x1public class MyJsonObject {
2
3"text") (
4public String text;
5
6"truncated") (
7public boolean truncated;
8
9"source") (
10publci String source;
11
12"entities") (
13public MyJsonEntities entities;
14
15//Getters/setters
16
17}
MyJsonEntities.java
101
2public class MyJsonEntities {
3
4"user_mentions") (
5public List<MyMentions> user_mentions;
6
7//Getters/Setters
8
9}
10
MyMentions.java
231
2
3public class MyMentions {
4
5"indices") (
6public ArrayList<Integer> indices;
7
8"screen_name") (
9public String screen_name;
10
11"id_str") (
12public String id_str;
13
14"name") (
15public String name;
16
17"id") (
18public int id;
19
20//Getters/setters
21}
22
23
Una volta create queste classi il parsing diventa un giochetto di poche righe di codice:
51
2Gson gson = new Gson();
3Reader reader = new InputStreamReader(source);
4MyJsonObject response = gson.fromJson(reader, MyJsonObject.class);
5
e voilà! Parsing del Json eseguito correttamente
Va sottolineato che la gerarchia e la struttura delle classi che create deve rispecchiare quella del file Json ricevuto! (MyJsonObject > MyJsonEntities > MyMentions)
Inutile dire che il parsing non va eseguito nel thread della UI ma eventualmente in un thread separato o in un AsyncTask
Esistono anche librerie che possono semplificarvi la vita, quali ION (https://github.com/koush/ion) soprattutto se per ricevere il Json avete bisogno di autenticazione (Nel repo di ION date un'occhiata all'esempio relativo a twitter)
Semplice esempio di parsing tramite Url
761
2
3MyJsonObject mJObject;
4
5...
6
7class LoadJson extends
8AsyncTask<Void, Boolean, MyJsonObject> {
9
10ProgressDialog p;
11
12
13protected void onPreExecute() {
14p = new ProgressDialog(context);
15p.setMessage("Loading...please wait");
16p.setIndeterminate(true);
17p.show();
18
19}
20
21
22protected JSObject doInBackground(Void... v) {
23
24InputStream source = retrieveStream(url);
25
26Gson gson = new Gson();
27
28Reader reader = new InputStreamReader(source);
29
30MyJsonObject response = gson.fromJson(reader, JSObject.class);
31return response;
32}
33
34
35protected void onPostExecute(MyJsonObject result) {
36
37mJObject = result;
38
39p.cancel();
40super.onPostExecute(result);
41}
42}
43new LoadJson().execute();
44
45
46private InputStream retrieveStream(String url) {
47
48DefaultHttpClient client = new DefaultHttpClient();
49
50HttpGet getRequest = new HttpGet(url);
51
52try {
53
54HttpResponse getResponse = client.execute(getRequest);
55final int statusCode = getResponse.getStatusLine().getStatusCode();
56
57if (statusCode != HttpStatus.SC_OK) {
58Log.w(context.getClass().getSimpleName(),
59"Error " + statusCode + " for URL " + url);
60return null;
61}
62
63HttpEntity getResponseEntity = getResponse.getEntity();
64return getResponseEntity.getContent();
65
66}
67catch (IOException e) {
68getRequest.abort();
69Log.w(context.getClass().getSimpleName(), "Error for URL " + url, e);
70}
71
72return null;
73
74}
75
76
Buon coding![]()
![]()