Bonjour,

Je doit parser un fichier JSON, je n'ai pas de soucis avec un fichier 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
{
    "Users": [
        {
            "firstname": "",
            "lastname": "",
            "login": "",
            "twitter": "",
            "mail": "",
	    "telephone" :
		{	 
			"fixe": "",
			"mobile": ""
		}
        },
        {
            "firstname": "",
            "lastname": "",
            "login": "",
            "twitter": "",
            "mail": "",
            "telephone" :
		{	 
			"fixe": "",
			"mobile": ""
		}
        }
    ]
}
J'utilise le code suivant :

UsersController
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
81
82
83
84
85
86
87
88
89
90
91
92
package com.example.parsingtest;
 
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.MalformedURLException;
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 = "http://XXX/users.json";
 
    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() {
	    downloadJsonFile();
	    try{
	        jp = jsonFactory.createJsonParser(jsonFile);
	        users = objectMapper.readValue(jp, Users.class);
	        userList = users.get("users");
	    } catch(JsonParseException e) {
	        e.printStackTrace();
	    } catch(IOException e) {
	        e.printStackTrace();
	    }
    }
 
    private void downloadJsonFile() {
	    try{
	        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();
	    } catch(MalformedURLException e) {
	        e.printStackTrace();
	    } catch(IOException e) {
	        e.printStackTrace();
	    }
    }
 
    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);
    }
 
}
User
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
package com.example.parsingtest;
 
public class User {
    private String firstname;
    private String lastname;
    private String login;
    private String twitter;
    private String mail;
    private Telephone telephone;
 
    public User() {
	    super();
	    this.firstname = "";
	    this.lastname = "";
	    this.login = "";
	    this.twitter = "";
	    this.mail = "";
	    this.telephone = null;
    }
 
    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.mail = 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 getMail() {
        return mail;
    }
 
    public void setMail(String mail) {
        this.mail = mail;
    }
 
	public Telephone getTelephone() {
		return telephone;
	}
 
	public void setTelephone(Telephone telephone) {
		this.telephone = telephone;
	}
 
}
Users
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
package com.example.parsingtest;
 
import java.util.ArrayList;
import java.util.HashMap;
 
public class Users extends HashMap<String, ArrayList<User>> {
 
    private static final long serialVersionUID = 1L;
 
}
Telephone
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
package com.example.parsingtest;
 
import org.json.JSONObject;
 
public class Telephone extends JSONObject {
 
	private String fixe;
	private String mobile;
 
	public String getFixe() {
		return fixe;
	}
	public void setFixe(String fixe) {
		this.fixe = fixe;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
 
 
 
 
 
 
}
MainActivity
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
package com.example.parsingtest;
 
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() {
			usersController.init();
			final StringBuilder str = new StringBuilder("user :\n ");
			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("Mail : ").append(u.getMail());
			    str.append("\n").append("Mobile : ").append(u.getTelephone().getMobile());
			    str.append("\n").append("Fixe : ").append(u.getTelephone().getFixe());
			    str.append("\n");
			}
			runOnUiThread(new Runnable() {
			        @Override
			        public void run() {
			            displayJson.setText(str.toString());
			        }
			    });
 
		    }
		};
		checkUpdate.start();
	    }
}
Mais j'ai un gros problème avec un fichier 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
{
"attribut": "",
"objetUsers" :
	{
    "Users": [
        {
            "firstname": "",
            "lastname": "",
            "login": "",
            "twitter": "",
            "mail": "",
	    "telephone" :
		{	 
			"fixe": "",
			"mobile": ""
		}
        },
        {
            "firstname": "",
            "lastname": "",
            "login": "",
            "twitter": "",
            "mail": "",
            "telephone" :
		{	 
			"fixe": "",
			"mobile": ""
		}
        }
    ]
}
}
Ces lignes en plus...
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
{
"attribut": "",
"objetUsers" :
	{
J'ai tenter de modifier avec le code suivant...

ObjetUsers
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
package com.example.parsingtest;
 
import org.json.JSONObject;
 
public class ObjetUsers extends JSONObject  {
 
	private Users users;
 
	public Users getUsers() {
		return users;
	}
 
	public void setUsers(Users objetUsers) {
		this.users = objetUsers;
	}
}
Users
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
package com.example.parsingtest;
 
import java.util.ArrayList;
 
public class Users {
 
	private ArrayList<User> listUser;
 
	public ArrayList<User> getListUser() {
		return listUser;
	}
 
	public void setListUser(ArrayList<User> listUser) {
		this.listUser = listUser;
	}
}
User
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
package com.example.parsingtest;
 
public class User {
    private String firstname;
    private String lastname;
    private String login;
    private String twitter;
    private String mail;
    private Telephone telephone;
 
    public User() {
	    super();
	    this.firstname = "";
	    this.lastname = "";
	    this.login = "";
	    this.twitter = "";
	    this.mail = "";
	    this.telephone = null;
    }
 
    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.mail = 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 getMail() {
        return mail;
    }
 
    public void setMail(String mail) {
        this.mail = mail;
    }
 
	public Telephone getTelephone() {
		return telephone;
	}
 
	public void setTelephone(Telephone telephone) {
		this.telephone = telephone;
	}
}
Telephone
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
package com.example.parsingtest;
 
import org.json.JSONObject;
 
public class Telephone extends JSONObject {
 
	private String fixe;
	private String mobile;
 
	public String getFixe() {
		return fixe;
	}
	public void setFixe(String fixe) {
		this.fixe = fixe;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
}
UsersController
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
81
82
83
84
85
86
87
88
89
90
91
package com.example.parsingtest;
 
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.MalformedURLException;
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 = "http://s414547850.onlinehome.fr/users.json";
 
    private ObjectMapper objectMapper = null;
    private JsonFactory jsonFactory = null;
    private JsonParser jp = null;
    private ArrayList<User> userList = null;
    private Parse parse = null;
    private File jsonOutputFile;
    private File jsonFile;
 
    public UsersController() {
	    objectMapper = new ObjectMapper();
	    jsonFactory = new JsonFactory();
    }
 
    public void init() {
	    downloadJsonFile();
	    try{
	        jp = jsonFactory.createJsonParser(jsonFile);
	        parse = objectMapper.readValue(jp, Parse.class);
	        userList = parse.getObjetUsers().getUsers().getListUser();
	    } catch(JsonParseException e) {
	        e.printStackTrace();
	    } catch(IOException e) {
	        e.printStackTrace();
	    }
    }
 
    private void downloadJsonFile() {
	    try{
	        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();
	    } catch(MalformedURLException e) {
	        e.printStackTrace();
	    } catch(IOException e) {
	        e.printStackTrace();
	    }
    }
 
    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);
    }
}
Parse
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
package com.example.parsingtest;
 
public class Parse {
 
	private String attribut;
	private ObjetUsers objetUsers;
 
	public String getAttribut() {
		return attribut;
	}
	public void setAttribut(String attribut) {
		this.attribut = attribut;
	}
	public ObjetUsers getObjetUsers() {
		return objetUsers;
	}
	public void setObjetUsers(ObjetUsers objetUsers) {
		this.objetUsers = objetUsers;
	}
}
... Mais cela ne fonctionne pas. Voici 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
21
22
23
24
25
01-05 21:51:51.649: D/dalvikvm(327): GC freed 5586 objects / 356272 bytes in 59ms
01-05 21:51:51.829: D/dalvikvm(327): GC freed 13527 objects / 590536 bytes in 54ms
01-05 21:51:52.049: D/dalvikvm(327): GC freed 12646 objects / 504056 bytes in 55ms
01-05 21:51:52.079: W/System.err(327): org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "Users" (Class com.example.parsingtest.ObjetUsers), not marked as ignorable
01-05 21:51:52.079: W/System.err(327):  at [Source: /sdcard/tutos-android/users.json; line: 5, column: 15] (through reference chain: com.example.parsingtest.Parse["objetUsers"]->com.example.parsingtest.ObjetUsers["Users"])
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:246)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.StdDeserializer.reportUnknownProperty(StdDeserializer.java:604)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.StdDeserializer.handleUnknownProperty(StdDeserializer.java:590)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.BeanDeserializer.handleUnknownProperty(BeanDeserializer.java:689)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:514)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:252)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:356)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:494)
01-05 21:51:52.079: W/System.err(327): 	at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350)
01-05 21:51:52.090: W/System.err(327): 	at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2376)
01-05 21:51:52.090: W/System.err(327): 	at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1087)
01-05 21:51:52.090: W/System.err(327): 	at com.example.parsingtest.UsersController.init(UsersController.java:41)
01-05 21:51:52.090: W/System.err(327): 	at com.example.parsingtest.MainActivity$2.run(MainActivity.java:37)
01-05 21:51:52.090: W/dalvikvm(327): threadid=15: thread exiting with uncaught exception (group=0x4001b188)
01-05 21:51:52.090: E/AndroidRuntime(327): Uncaught handler: thread Thread-8 exiting due to uncaught exception
01-05 21:51:52.090: E/AndroidRuntime(327): java.lang.NullPointerException
01-05 21:51:52.090: E/AndroidRuntime(327): 	at com.example.parsingtest.MainActivity$2.run(MainActivity.java:39)
01-05 21:51:52.109: I/dalvikvm(327): threadid=7: reacting to signal 3
01-05 21:51:52.109: E/dalvikvm(327): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
Le problème et que je sais même pas si je m'y prend bien au niveau de la structure du fichier Json, et du coup de mes classes. Est-ce que le problème viens de la structure ou des quelques lignes suivantes ?

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
public void init() {
	    downloadJsonFile();
	    try{
	        jp = jsonFactory.createJsonParser(jsonFile);
	        parse = objectMapper.readValue(jp, Parse.class);
	        userList = parse.getObjetUsers().getUsers().getListUser();
	    } catch(JsonParseException e) {
	        e.printStackTrace();
	    } catch(IOException e) {
	        e.printStackTrace();
	    }
    }
Merci d'avance...