IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

Parsing JSON


Sujet :

Android

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    Points : 11
    Points
    11
    Par défaut Parsing JSON
    Bonjour,

    J'ai un petit souci pour parser du JSON.

    Pour m'aider, j'ai repris cet exemple qui marche très bien : http://www.androidhive.info/2012/01/...sing-tutorial/

    Le fichier JSON est de type :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    {
    ****"contacts":*[
    ********{
    ****************"id":*"c200",
    ****************"name":*"Ravi*Tamada",
    ****************"email":*"ravi@gmail.com",
    ****************"address":*"xx-xx-xxxx,x*-*street,*x*-*country",
    ****************"gender"*:*"male",
    ****************"phone":*{
    ********************"mobile":*"*+91*0000000000",
    ********************"home":*"00*000000",
    ********************"office":*"00*000000"
    ****************}
    ********},
    ********{
    ****************"id":*"c201",
    ****************"name":*"Johnny*Depp",
    ****************"email":*"johnny_depp@gmail.com",
    ****************"address":*"xx-xx-xxxx,x*-*street,*x*-*country",
    ****************"gender"*:*"male",
    ****************"phone":*{
    ********************"mobile":*"*+91*0000000000",
    ********************"home":*"00*000000",
    ********************"office":*"00*000000"
    ****************}
    ********},
    ********.
    ********.
    ********.
    ********.
    **]
    }
    Mais le problème et que je dois parser un fichier du type :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    {
    "expirationDate":"2012-12-16*3:45",
    "lines":
    {
    "line":[
    {
    **********"color"*********:*"(255,0,0)",
    **********"id"************:*"11821949021891694",
    **********"name"**********:*"Basso*Cambo*/*Balma-Gramont",
    **********"shortName"*****:*"A",**********
    **********"network"*******:*"Tisséo",
    **********"transportMode"*:
    *****************{*********
    ******************"id"*****:"13792273858822586",
    ******************"article":*"le",
    ******************"name"***:*"métro"
    ****************}*************************
    ********}
    ********,{
    **********"color"*********:*"(255,94,22)",
    **********"id"************:*"11821949021891902",
    **********"name"**********:*"Navette*aéroport",
    **********"shortName"*****:*"AERO",**********
    **********"network"*******:*"Tisséo",
    **********"transportMode"*:
    *****************{*********
    ******************"id"*****:"13792273858822585",
    ******************"article":*"le",
    ******************"name"***:*"bus"
    ****************}*************************
    ********}
    ********,
    .
    .
    .
    J'ai donc essayé de modifier le code du tutoriel cité plus haut de cette manière(mais rien ne s'affiche, par contre l'application ne plante pas) :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    private static String url = "http://pt.data.tisseo.fr/linesList?format=json";
     
        // JSON Node names
        private static final String TAG_expirationDate = "expirationDate";
        private static final String TAG_line = "line";
        private static final String TAG_color = "color";
        private static final String TAG_id = "id";
        private static final String TAG_name = "name";
        private static final String TAG_shortName = "shortName";
        private static final String TAG_network = "network";
        private static final String TAG_transportMode = "transportMode";
        private static final String TAG_id_transportMode = "id_transportMode";
        private static final String TAG_article = "article";
        private static final String TAG_name_transportMode = "name_transportMode";
     
        // contacts JSONArray
        JSONArray line = null;
        String expirationDate = null;
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
     
            // Hashmap for ListView
            ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
     
            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();
     
            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(url);
     
            try {
                expirationDate = json.getString(TAG_expirationDate);
                // Getting Array of Contacts
                line = json.getJSONArray(TAG_line);
     
                // looping through All Contacts
                for(int i = 0; i < line.length(); i++){
                    JSONObject l = line.getJSONObject(i);
     
                    // Storing each json item in variable
                    String color = l.getString(TAG_color);
                    String id = l.getString(TAG_id);
                    String name = l.getString(TAG_name);
                    String shortName = l.getString(TAG_shortName);
                    String network = l.getString(TAG_network);
     
                    // Phone number is agin JSON Object
                    JSONObject transportMode = l.getJSONObject(TAG_transportMode);
                    String id_transportMode = transportMode.getString(TAG_id_transportMode);
                    String article = transportMode.getString(TAG_article);
                    String name_transportMode = transportMode.getString(TAG_name_transportMode);
     
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
     
                    // adding each child node to HashMap key => value
                    map.put(TAG_name, name);
                    map.put(TAG_shortName, shortName);
                    map.put(TAG_network, network);
                    map.put(TAG_name_transportMode, name_transportMode);
     
                    // adding HashList to ArrayList
                    contactList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
    Je pense que le probleme vient du début du fichier mais je ne trouve pas de solution...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    {
    "expirationDate":"2012-12-16*3:45",
    "lines":
    Quelqu'un aurait une idée du problème ?

    Merci d'avance pour votre aide.

  2. #2
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    C'est pas franchement très élégant comme solution.

    Crée plutôt des beans correspondant à ton json (un attribut par tag de ton json) et utilise jackson qui fera le parsing et la population du bean pour toi: http://nbenbourahla.developpez.com/t...ckson-android/
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  3. #3
    Membre à l'essai
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    Points : 11
    Points
    11
    Par défaut
    C'est vrai que ça a l'air mieux, mais cette méthode ne marche pas , même si je ne modifie rien a l'exemple...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    12-18 18:52:20.194: E/dalvikvm(381): Could not find class 'org.codehaus.jackson.map.ObjectMapper', referenced from method com.example.jsonjacksontest.UsersController.<init>
    12-18 18:52:20.204: W/dalvikvm(381): VFY: unable to resolve new-instance 563 (Lorg/codehaus/jackson/map/ObjectMapper;) in Lcom/example/jsonjacksontest/UsersController;
    12-18 18:52:20.204: D/dalvikvm(381): VFY: replacing opcode 0x22 at 0x000e
    12-18 18:52:20.204: D/dalvikvm(381): VFY: dead code 0x0010-001c in Lcom/example/jsonjacksontest/UsersController;.<init> ()V
    12-18 18:52:20.214: I/dalvikvm(381): Could not find method org.codehaus.jackson.JsonFactory.createJsonParser, referenced from method com.example.jsonjacksontest.UsersController.init
    12-18 18:52:20.214: W/dalvikvm(381): VFY: unable to resolve virtual method 3503: Lorg/codehaus/jackson/JsonFactory;.createJsonParser (Ljava/io/File;)Lorg/codehaus/jackson/JsonParser;
    12-18 18:52:20.224: D/dalvikvm(381): VFY: replacing opcode 0x6e at 0x0007
    12-18 18:52:20.224: W/dalvikvm(381): VFY: unable to resolve exception class 561 (Lorg/codehaus/jackson/JsonParseException;)
    12-18 18:52:20.224: W/dalvikvm(381): VFY: unable to find exception handler at addr 0x28
    12-18 18:52:20.224: W/dalvikvm(381): VFY:  rejected Lcom/example/jsonjacksontest/UsersController;.init ()V
    12-18 18:52:20.224: W/dalvikvm(381): VFY:  rejecting opcode 0x0d at 0x0028
    12-18 18:52:20.224: W/dalvikvm(381): VFY:  rejected Lcom/example/jsonjacksontest/UsersController;.init ()V
    12-18 18:52:20.224: W/dalvikvm(381): Verifier rejected class Lcom/example/jsonjacksontest/UsersController;
    12-18 18:52:20.234: D/AndroidRuntime(381): Shutting down VM
    12-18 18:52:20.234: W/dalvikvm(381): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
    12-18 18:52:20.254: E/AndroidRuntime(381): FATAL EXCEPTION: main
    12-18 18:52:20.254: E/AndroidRuntime(381): java.lang.VerifyError: com.example.jsonjacksontest.UsersController
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at com.example.jsonjacksontest.MainActivity.onCreate(MainActivity.java:19)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at android.app.ActivityThread.access$2300(ActivityThread.java:125)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at android.os.Handler.dispatchMessage(Handler.java:99)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at android.os.Looper.loop(Looper.java:123)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at android.app.ActivityThread.main(ActivityThread.java:4627)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at java.lang.reflect.Method.invokeNative(Native Method)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at java.lang.reflect.Method.invoke(Method.java:521)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    12-18 18:52:20.254: E/AndroidRuntime(381): 	at dalvik.system.NativeStart.main(Native Method)

  4. #4
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Attention aussi à la fonction getJSONFromUrl(String url) du premier tuto qui est complètement buguée (et doit être appelée dans un thread)..
    (NullPointerException en cas de probleme, non gestion du code retour HTTP, non gestion des exceptions tout court d'ailleurs, non gestion de l'encodage et du charset,...)
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  5. #5
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    Et accessoirement, l'erreur est due au fait que tu n'as pas intégré jackson dans les dépendances de ton projet.

    A savoir jackson-core, jackson-databinding et éventuellement jackson-annotations

    http://jackson.codehaus.org/
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  6. #6
    Membre à l'essai
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    Points : 11
    Points
    11
    Par défaut
    effectivement je les avais mis dans le dossier lib au lieu de libs et sa ne marchais pas par contre j'ai deux fichier jar "jackson-core-asl-1.8.5.jar" et "jackson-mapper-asl-1.8.5.jar"
    C'est la même chose que le lien ?

    Mais le projet d'exemple (http://nbenbourahla.developpez.com/t...ckson-android/) ne fonctionne toujours pas :/

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    usersController.findAll()
    renvoie un nullPointerException.
    cette fonction retourne userList donc je suppose donc que c'est les lignes
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    users = objectMapper.readValue(jp, Users.class);
    userList = users.get("Users");
    userList reste null. Est-ce que cela vient d'un problème lors du téléchargement du fichier ?

    Code complet : http://nbenbourahla.developpez.com/t...ckson-android/

  7. #7
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    a quelle ligne exactement as tu la NPE?
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  8. #8
    Membre à l'essai
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    Points : 11
    Points
    11
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    for(User u : usersController.findAll()) {
    dans JsonParserMainActivity

  9. #9
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Parceque dans le tutorial toute les exceptions sont "catchées" et passées sous silence (aucune remontée à l'appelant), même pour les exceptions indiquant clairement que la fonction n'a pas pu effectué son boulot....

    Commencez par virer tous les try/catch
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  10. #10
    Membre à l'essai
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    Points : 11
    Points
    11
    Par défaut
    J'ai toujours ce NPE

    Il n'y a personne qui a réussi à faire fonctionner ce tuto et qui a trouver l'erreur ? :p

    Le logcat :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    12-26 13:21:07.646: W/System.err(275): java.net.SocketException: Permission denied (maybe missing INTERNET permission)
    12-26 13:21:07.656: W/System.err(275): 	at org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocketImpl(Native Method)
    12-26 13:21:07.666: W/System.err(275): 	at org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocket(OSNetworkSystem.java:187)
    12-26 13:21:07.666: W/System.err(275): 	at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:266)
    12-26 13:21:07.666: W/System.err(275): 	at java.net.Socket.checkClosedAndCreate(Socket.java:872)
    12-26 13:21:07.666: W/System.err(275): 	at java.net.Socket.connect(Socket.java:1019)
    12-26 13:21:07.666: W/System.err(275): 	at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:62)
    12-26 13:21:07.666: W/System.err(275): 	at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager$ConnectionPool.getHttpConnection(HttpConnectionManager.java:145)
    12-26 13:21:07.666: W/System.err(275): 	at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager.getConnection(HttpConnectionManager.java:67)
    12-26 13:21:07.676: W/System.err(275): 	at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getHTTPConnection(HttpURLConnection.java:821)
    12-26 13:21:07.676: W/System.err(275): 	at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:807)
    12-26 13:21:07.676: W/System.err(275): 	at com.example.jsonjacksontest.UsersController.downloadJsonFile(UsersController.java:51)
    12-26 13:21:07.676: W/System.err(275): 	at com.example.jsonjacksontest.UsersController.init(UsersController.java:37)
    12-26 13:21:07.676: W/System.err(275): 	at com.example.jsonjacksontest.MainActivity$2.run(MainActivity.java:42)
    12-26 13:21:07.676: W/dalvikvm(275): threadid=15: thread exiting with uncaught exception (group=0x4001b188)
    12-26 13:21:07.685: E/AndroidRuntime(275): Uncaught handler: thread Thread-8 exiting due to uncaught exception
    12-26 13:21:07.685: E/AndroidRuntime(275): java.lang.NullPointerException
    12-26 13:21:07.685: E/AndroidRuntime(275): 	at com.example.jsonjacksontest.MainActivity$2.run(MainActivity.java:51)
    12-26 13:21:07.696: I/dalvikvm(275): threadid=7: reacting to signal 3
    12-26 13:21:07.696: E/dalvikvm(275): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
    Et mon code complet :

    MainActivity.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    package com.example.jsonjacksontest;
     
    import java.io.IOException;
     
    import org.codehaus.jackson.JsonParseException;
     
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
     
    public class MainActivity extends Activity {
     
    	private UsersController usersController;
        private TextView displayJson;
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
     
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		usersController = new UsersController();
     
    		displayJson = (TextView) findViewById(R.id.jsonDisplay);
     
    		Button startParsing = (Button) findViewById(R.id.startParsing);
    		startParsing.setOnClickListener(new OnClickListener() {
    		    @Override
    		    public void onClick(View view) {
    			gettingJson();
    		    }
    		});
        }
     
        final void gettingJson() {
     
    		final Thread checkUpdate = new Thread() {
    		    public void run() {
    			try {
    				usersController.init();
    			} catch (JsonParseException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			final StringBuilder str = new StringBuilder("user : ");
    			for (User u : usersController.findAll()) {
    			    str.append("\n").append("first name : ").append(u.getFirstname());
    			    str.append("\n").append("last name : ").append(u.getLastname());
    			    str.append("\n").append("login : ").append(u.getLogin());
    			    str.append("\n").append("twitter : ").append(u.getTwitter());
    			    str.append("\n").append("Web : ").append(u.getWeb());
    			}
    			runOnUiThread(new Runnable() {
    			        @Override
    			        public void run() {
    			            displayJson.setText(str.toString());
    			        }
    			    });
     
    		    }
    		};
    		checkUpdate.start();
    	    }
    }
    User.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    package com.example.jsonjacksontest;
     
    public class User {
        private String firstname;
        private String lastname;
        private String login;
        private String twitter;
        private String web;
     
        public User() {
     
    	    super();
    	    this.firstname = "";
    	    this.lastname = "";
    	    this.login = "";
    	    this.twitter = "";
    	    this.web = "";
        }
     
        public User(String firstName, String lastName, String login,
                    String twitter, String web) {
    	    super();
    	    this.firstname = firstName;
    	    this.lastname = lastName;
    	    this.login = login;
    	    this.twitter = twitter;
    	    this.web = web;
        }
     
        public String getFirstname() {
            return firstname;
        }
     
        public void setFirstname(String firstName) {
            this.firstname = firstName;
        }
     
        public String getLastname() {
            return lastname;
        }
     
        public void setLastname(String lastName) {
            this.lastname = lastName;
        }
     
        public String getLogin() {
            return login;
        }
     
        public void setLogin(String login) {
            this.login = login;
        }
     
        public String getTwitter() {
            return twitter;
        }
     
        public void setTwitter(String twitter) {
            this.twitter = twitter;
        }
     
        public String getWeb() {
            return web;
        }
     
        public void setWeb(String web) {
            this.web = web;
        }
     
    }
    Users.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    package com.example.jsonjacksontest;
     
    import java.util.ArrayList;
    import java.util.HashMap;
     
    public class Users extends HashMap<String, ArrayList<User>> {
     
        private static final long serialVersionUID = 1L;
     
    }
    UsersController.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    package com.example.jsonjacksontest;
     
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
     
    import org.codehaus.jackson.JsonFactory;
    import org.codehaus.jackson.JsonParseException;
    import org.codehaus.jackson.JsonParser;
    import org.codehaus.jackson.map.ObjectMapper;
     
    import android.os.Environment;
     
    public class UsersController {
     
        private static final String DL_URL = "";
     
        private ObjectMapper objectMapper = null;
        private JsonFactory jsonFactory = null;
        private JsonParser jp = null;
        private ArrayList<User> userList = null;
        private Users users = null;
        private File jsonOutputFile;
        private File jsonFile;
     
        public UsersController() {
    	    objectMapper = new ObjectMapper();
    	    jsonFactory = new JsonFactory();
        }
     
        public void init() throws JsonParseException, IOException {
    	    downloadJsonFile();
    	        jp = jsonFactory.createJsonParser(jsonFile);
    	        users = objectMapper.readValue(jp, Users.class);
    	        userList = users.get("Users");
        }
     
        private void downloadJsonFile() throws IOException {
     
    		createFileAndDirectory();
    		URL url = new URL(UsersController.DL_URL);
    		HttpURLConnection urlConnection;
    		urlConnection = (HttpURLConnection) url.openConnection();
    		urlConnection.setRequestMethod("GET");
    		urlConnection.setDoOutput(true);
    		urlConnection.connect();
    		FileOutputStream fileOutput = new FileOutputStream(jsonFile);
    		InputStream inputStream = urlConnection.getInputStream();
    		byte[] buffer = new byte[1024];
    		int bufferLength = 0;
    		while((bufferLength = inputStream.read(buffer)) > 0) {
    			fileOutput.write(buffer, 0, bufferLength);
    		}
    		fileOutput.close();
        }
     
        private void createFileAndDirectory() throws FileNotFoundException {
     
    	    final String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    	    final String meteoDirectory_path = extStorageDirectory + "/tutos-android";
    	    jsonOutputFile = new File(meteoDirectory_path, "/");
    	    if(jsonOutputFile.exists() == false)
    	        jsonOutputFile.mkdirs();
    	    jsonFile = new File(jsonOutputFile, "users.json");
        }
     
        public ArrayList<User> findAll() {
        	return userList;
        }
     
        public User findById(int id) {
        	return userList.get(id);
        }
     
    }

  11. #11
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    La NPE n'est qu'une conséquence (à corriger également, tu dois tenter d'exécuter une méthode sur un objet qui est potentiellement null à la ligne 52 de ta classe MainActivity.

    La source du problème est la suivante:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    12-26 13:21:07.646: W/System.err(275): java.net.SocketException: Permission denied (maybe missing INTERNET permission)
    Et, pour le coup, c'est relativement explicite, non?
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  12. #12
    Membre à l'essai
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    Points : 11
    Points
    11
    Par défaut
    En effet,
    J'ai donc rajouter les lignes
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    dans le AndroidManifest.xml. Sa marche Merci.

    Mais du coup j'en reviens à mon problème de base, j'ai du mal avec la structure de mon fichier Json...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    {
    "expirationDate":"2012-12-30 3:45",
    "lines":
    {
    "line":[
    {
    	  "color"         : "(255,0,0)",
    	  "id"            : "11821949021891694",
    	  "name"          : "Basso Cambo / Balma-Gramont",
    	  "shortName"     : "A",	  
    	  "network"       : "Tisséo",
    	  "transportMode" :
    	 	{	 
    		  "id"     :"13792273858822586",
    		  "article": "le",
    		  "name"   : "métro"
    		} 			
    	}
            ,{
    	  "color"         : "(255,94,22)",
    	  "id"            : "11821949021891902",
    	  "name"          : "Navette aéroport",
    	  "shortName"     : "AERO",	  
    	  "network"       : "Tisséo",
    	  "transportMode" :
    	 	{	 
    		  "id"     :"13792273858822585",
    		  "article": "le",
    		  "name"   : "bus"
    		} 			
    	}
            ,{}
    ]
    }
    }
    J'ai une classe line :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    package com.example.jsonjacksontest;
     
    public class Line {
        private String color;
        private String name;
        private String shortName;
     
        public Line() {
    	    super();
    	    this.color = "";
    	    this.name = "";
    	    this.shortName = "";
        }
     
        public Line(String color, String name, String shortName) {
    	    super();
    	    this.color = color;
    	    this.name = name;
    	    this.shortName = shortName;
        }
     
    	/**
             * @return the color
             */
    	public String getColor() {
    		return color;
    	}
     
    	/**
             * @param color the color to set
             */
    	public void setColor(String color) {
    		this.color = color;
    	}
     
    	/**
             * @return the name
             */
    	public String getName() {
    		return name;
    	}
     
    	/**
             * @param name the name to set
             */
    	public void setName(String name) {
    		this.name = name;
    	}
     
    	/**
             * @return the shortName
             */
    	public String getShortName() {
    		return shortName;
    	}
     
    	/**
             * @param shortName the shortName to set
             */
    	public void setShortName(String shortName) {
    		this.shortName = shortName;
    	}
     
     
     
    }
    une classe Lines :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    package com.example.jsonjacksontest;
     
    import java.util.ArrayList;
    import java.util.HashMap;
     
    public class Lines extends HashMap<String, ArrayList<Line>> {
     
        private static final long serialVersionUID = 1L;
     
    }
    et une classe LinesController :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    package com.example.jsonjacksontest;
     
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
     
    import org.codehaus.jackson.JsonFactory;
    import org.codehaus.jackson.JsonParseException;
    import org.codehaus.jackson.JsonParser;
    import org.codehaus.jackson.map.ObjectMapper;
     
    import android.os.Environment;
     
    public class LinesController {
     
        private static final String DL_URL = "http://pt.data.tisseo.fr/linesList?format=json";
     
        private ObjectMapper objectMapper = null;
        private JsonFactory jsonFactory = null;
        private JsonParser jp = null;
        private ArrayList<Line> lineList = null;
        private Lines lines = null;
        private File jsonOutputFile;
        private File jsonFile;
     
        public LinesController() {
    	    objectMapper = new ObjectMapper();
    	    jsonFactory = new JsonFactory();
        }
     
        public void init() throws JsonParseException, IOException {
    	    downloadJsonFile();
    	        jp = jsonFactory.createJsonParser(jsonFile);
    	        lines = objectMapper.readValue(jp, Lines.class);
    	        lineList = lines.get("lines");
        }
     
        private void downloadJsonFile() throws IOException {
     
    		createFileAndDirectory();
    		URL url = new URL(LinesController.DL_URL);
    		HttpURLConnection urlConnection;
    		urlConnection = (HttpURLConnection) url.openConnection();
    		urlConnection.setRequestMethod("GET");
    		urlConnection.setDoOutput(true);
    		urlConnection.connect();
    		FileOutputStream fileOutput = new FileOutputStream(jsonFile);
    		InputStream inputStream = urlConnection.getInputStream();
    		byte[] buffer = new byte[1024];
    		int bufferLength = 0;
    		while((bufferLength = inputStream.read(buffer)) > 0) {
    			fileOutput.write(buffer, 0, bufferLength);
    		}
    		fileOutput.close();
        }
     
        private void createFileAndDirectory() throws FileNotFoundException {
     
    	    final String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    	    final String meteoDirectory_path = extStorageDirectory + "/Toulouse";
    	    jsonOutputFile = new File(meteoDirectory_path, "/");
    	    if(jsonOutputFile.exists() == false)
    	        jsonOutputFile.mkdirs();
    	    jsonFile = new File(jsonOutputFile, "lines.json");
        }
     
        public ArrayList<Line> findAll() {
        	return lineList;
        }
     
        public Line findById(int id) {
        	return lineList.get(id);
        }
     
    }
    mais le logcat m'affiche :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    12-29 17:41:07.307: D/dalvikvm(402): GC freed 6700 objects / 390024 bytes in 138ms
    12-29 17:41:07.776: D/dalvikvm(402): GC freed 11955 objects / 524848 bytes in 122ms
    12-29 17:41:08.016: W/System.err(402): org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
    12-29 17:41:08.016: W/System.err(402):  at [Source: /sdcard/Toulouse/lines.json; line: 2, column: 1]
    12-29 17:41:08.028: W/System.err(402): 	at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:198)
    12-29 17:41:08.028: W/System.err(402): 	at org.codehaus.jackson.map.deser.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:149)
    12-29 17:41:08.028: W/System.err(402): 	at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:107)
    12-29 17:41:08.028: W/System.err(402): 	at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:97)
    12-29 17:41:08.028: W/System.err(402): 	at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
    12-29 17:41:08.036: W/System.err(402): 	at org.codehaus.jackson.map.deser.MapDeserializer._readAndBind(MapDeserializer.java:235)
    12-29 17:41:08.036: W/System.err(402): 	at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:165)
    12-29 17:41:08.036: W/System.err(402): 	at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:25)
    12-29 17:41:08.036: W/System.err(402): 	at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2376)
    12-29 17:41:08.036: W/System.err(402): 	at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1087)
    12-29 17:41:08.046: W/System.err(402): 	at com.example.jsonjacksontest.LinesController.init(LinesController.java:39)
    12-29 17:41:08.056: W/System.err(402): 	at com.example.jsonjacksontest.MainActivity$2.run(MainActivity.java:42)
    12-29 17:41:08.056: W/dalvikvm(402): threadid=15: thread exiting with uncaught exception (group=0x4001b188)
    12-29 17:41:08.066: E/AndroidRuntime(402): Uncaught handler: thread Thread-8 exiting due to uncaught exception
    12-29 17:41:08.066: E/AndroidRuntime(402): java.lang.NullPointerException
    12-29 17:41:08.066: E/AndroidRuntime(402): 	at com.example.jsonjacksontest.MainActivity$2.run(MainActivity.java:51)
    12-29 17:41:08.086: I/dalvikvm(402): threadid=7: reacting to signal 3
    12-29 17:41:08.086: E/dalvikvm(402): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
    12-29 17:41:09.567: I/Process(402): Sending signal. PID: 402 SIG: 9

  13. #13
    Membre à l'essai
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    Points : 11
    Points
    11
    Par défaut
    Que doit-on faire pour le transportMode ? J'ai créer dans la classe line, un attribut de type TransportMode. TransportMode étant une classe possédant les attributs "id", "article" et "name". C'est bien cela qu'il faut faire ?
    Suis-je obligé de récupéré toutes les valeurs du fichier ? je me fiche de "expirationDate"

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    {
    "expirationDate":"2012-12-30 3:45",
    "lines":
    {
    "line":[
    {
    	  "color"         : "(255,0,0)",
    	  "id"            : "11821949021891694",
    	  "name"          : "Basso Cambo / Balma-Gramont",
    	  "shortName"     : "A",	  
    	  "network"       : "Tisséo",
    	  "transportMode" :
    	 	{	 
    		  "id"     :"13792273858822586",
    		  "article": "le",
    		  "name"   : "métro"
    		} 			
    	}
            ,{
    	  "color"         : "(255,94,22)",
    	  "id"            : "11821949021891902",
    	  "name"          : "Navette aéroport",
    	  "shortName"     : "AERO",	  
    	  "network"       : "Tisséo",
    	  "transportMode" :
    	 	{	 
    		  "id"     :"13792273858822585",
    		  "article": "le",
    		  "name"   : "bus"
    		} 			
    	}
            ,{}
    ]
    }
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. problème de parsing json
    Par diengkals dans le forum Android
    Réponses: 6
    Dernier message: 10/05/2011, 15h02
  2. parsing json erreur nullpointExcepetion
    Par diengkals dans le forum Android
    Réponses: 7
    Dernier message: 14/04/2011, 12h24
  3. parse json dans un code javascript
    Par chahira83 dans le forum jQuery
    Réponses: 5
    Dernier message: 11/12/2008, 16h39
  4. parse JSON et expression régulière
    Par Bruno2000 dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 30/06/2006, 16h39

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo