Bonjour,

J'ai le fichier Json suivant:

Code json : 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
{
    "title": "Person",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}

J'aimerais bien récupérer la valeur du champ description.....

Je suis arrivé à avoir le champ title, en utilisant le code suivant:

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
 
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
 
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author 
 */
public class ClassMain {
 
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
 
        try {
 
            Object obj = parser.parse(new FileReader("C:\\Users\\User\\Documents\\NetBeansProjects\\TestJsonProject\\src\\ressources\\file.json"));
 
            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject);
 
            String title = (String) jsonObject.get("title");
            System.out.println(title);
 
 
            // loop array
            JSONArray msg = (JSONArray) jsonObject.get("age");
 
            for (int i = 0; i < msg.length(); i++) {
 
                JSONObject jsonNumber = (JSONObject) msg.get(i);
                String natural = (String) jsonNumber.get("description");
                System.out.println(" --> "+natural);
            }
 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JSONException ex) {
            Logger.getLogger(ClassMain.class.getName()).log(Level.SEVERE, null, ex);
        }
 
    }
}
le problème c'est que lors de l'exécution, j'ai eu cette erreur:

Exception in thread "main" java.lang.NullPointerException
at ClassMain.main(ClassMain.java:43)
Java Result: 1
Avec la ligne 43 correspond à:
for (int i = 0; i < msg.length(); i++) {
Je me demande comment faire pour régler ce problème?

Merci en avance.