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

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    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 confirmé
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    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/

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

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    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 confirmé

    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
    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,...)

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

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    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/

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

    Informations forums :
    Inscription : Novembre 2012
    Messages : 13
    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/

+ 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