CERCA
PER MODELLO
FullScreen Chatbox! :)

Utente del giorno: gianpassa con ben 1 Thanks ricevuti nelle ultime 24 ore
Utente della settimana: carotix con ben 11 Thanks ricevuti negli ultimi sette giorni
Utente del mese: megthebest con ben 26 Thanks ricevuti nell'ultimo mese

Visualizzazione dei risultati da 1 a 2 su 2
Discussione:

[SNIPPET] Json Parsing

Se questa discussione ti è stata utile, ti preghiamo di lasciare un messaggio di feedback in modo che possa essere preziosa in futuro anche per altri utenti come te!
  1. #1
    Androidiani Power User L'avatar di cesco


    Registrato dal
    Sep 2010
    Località
    Bg
    Messaggi
    5,018
    Smartphone
    TYTN2,desire,desireHD, oneX

    Ringraziamenti
    54
    Ringraziato 1,346 volte in 724 Posts
    Predefinito

    [SNIPPET] Json Parsing

    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:
    {
    "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
    }
    view raw twitter.json hosted with ❤ by GitHub


    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
    x
     
    1
    public class MyJsonObject {
    2
    3
    @SerializedName("text")
    4
    public String text;
    5
    6
    @SerializedName("truncated")
    7
    public boolean truncated;
    8
    9
    @SerializedName("source")
    10
    publci String source;
    11
    12
    @SerializedName("entities")
    13
    public MyJsonEntities entities;
    14
    15
    //Getters/setters
    16
    17
    }


    MyJsonEntities.java
    10
     
    1
    2
    public class MyJsonEntities {
    3
    4
    @SerializedName("user_mentions")
    5
    public List<MyMentions> user_mentions;
    6
    7
    //Getters/Setters
    8
    9
    }
    10


    MyMentions.java
    23
     
    1
    2
    3
    public class MyMentions {
    4
    5
    @SerializedName("indices")
    6
    public ArrayList<Integer> indices;
    7
    8
    @SerializedName("screen_name")
    9
    public String screen_name;
    10
    11
    @SerializedName("id_str")
    12
    public String id_str;
    13
    14
    @SerializedName("name")
    15
    public String name;
    16
    17
    @SerializedName("id")
    18
    public int id;
    19
    20
    //Getters/setters
    21
    }
    22
    23



    Una volta create queste classi il parsing diventa un giochetto di poche righe di codice:

    5
     
    1
    2
    Gson gson = new Gson();
    3
    Reader reader = new InputStreamReader(source);
    4
    MyJsonObject 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
    76
     
    1
    2
    3
    MyJsonObject mJObject;
    4
    5
    ...
    6
    7
    class LoadJson extends
    8
            AsyncTask<Void, Boolean, MyJsonObject> {
    9
    10
                ProgressDialog p;
    11
    12
                @Override
    13
                protected void onPreExecute() {
    14
                    p = new ProgressDialog(context);
    15
                    p.setMessage("Loading...please wait");
    16
                    p.setIndeterminate(true);
    17
                    p.show();
    18
    19
                }
    20
    21
                @Override
    22
                protected JSObject doInBackground(Void... v) {
    23
    24
                    InputStream source = retrieveStream(url);
    25
    26
                    Gson gson = new Gson();
    27
    28
                    Reader reader = new InputStreamReader(source);
    29
    30
                    MyJsonObject response = gson.fromJson(reader, JSObject.class);
    31
                    return response;
    32
                }
    33
    34
                @Override
    35
                protected void onPostExecute(MyJsonObject result) {
    36
    37
                    mJObject = result;
    38
    39
                    p.cancel();
    40
                    super.onPostExecute(result);
    41
                }
    42
            }
    43
         new LoadJson().execute();
    44
    45
    46
    private InputStream retrieveStream(String url) {
    47
    48
            DefaultHttpClient client = new DefaultHttpClient(); 
    49
    50
            HttpGet getRequest = new HttpGet(url);
    51
    52
            try {
    53
    54
                HttpResponse getResponse = client.execute(getRequest);
    55
                final int statusCode = getResponse.getStatusLine().getStatusCode();
    56
    57
                if (statusCode != HttpStatus.SC_OK) { 
    58
                    Log.w(context.getClass().getSimpleName(), 
    59
                            "Error " + statusCode + " for URL " + url); 
    60
                    return null;
    61
                }
    62
    63
                HttpEntity getResponseEntity = getResponse.getEntity();
    64
                return getResponseEntity.getContent();
    65
    66
            } 
    67
            catch (IOException e) {
    68
                getRequest.abort();
    69
                Log.w(context.getClass().getSimpleName(), "Error for URL " + url, e);
    70
            }
    71
    72
            return null;
    73
    74
        }
    75
    76


    Buon coding
    Ultima modifica di cesco; 09-05-14 alle 10:30
    Follow me on:
    <!-- Place this tag where you want the widget to render. -->
    <div class="g-person" data-width="180" data-href="//plus.google.com/113012341277613226011" data-theme="dark" data-rel="author"></div>

    <!-- Place this tag after the last widget tag. -->
    <script type="text/javascript">
    window.___gcfg = {lang: 'it'};

    (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
    })();
    </script>
    <br>
    <a class="twitter-timeline" href="https://twitter.com/xcesco89" data-widget-id="398762031488040960">Tweets di @xcesco89</a>
    <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementB yId(id)){js=d.createElement(s);js.id=id;js.src=p+" ://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}} (document,"script","twitter-wjs");</script>
    Androidiani app
    Estensione Androidiani per Google Chrome

  2.  
  3. #2
    Senior Droid


    Registrato dal
    May 2010
    Località
    Rivoli
    Messaggi
    426

    Ringraziamenti
    6
    Ringraziato 48 volte in 47 Posts
    Predefinito

    IntereFFante!
    Avevo fatto la stessa cosa lato server, in C#, ma il parsing su client avevo dovuto farlo a manina...

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire risposte
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Torna su
Privacy Policy