web-dev-qa-db-fra.com

Extraction de données d'un tableau JSON

Je sais que c'est un tableau, mais je suis complètement nouveau en JSON et j'ai besoin d'aide pour comprendre sa structure. Voici ma tentative d'extraction de données:

String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("name"));

Mes données JSON que je possède vont comme ceci: 

 {
"sports": [
    {
        "name": "basketball",
        "id": 40,
        "uid": "s:40",
        "leagues": [
            {
                "name": "National Basketball Assoc.",
                "abbreviation": "nba",
                "id": 46,
                "uid": "s:40~l:46",
                "groupId": 7,
                "shortName": "NBA",
                "athletes": []
            }
        ]
    }
],
"resultsOffset": 10,
"resultsLimit": 10,
"resultsCount": 1,
"timestamp": "2013-11-18T03:15:43Z",
"status": "success"
}

Je n'ai pas vraiment une bonne compréhension de ce genre de choses et toute l'aide est appréciée. 

6
user2855405

Voici l'idée:

JSONObject root = new JSONObject(yourJsonString);
JSONArray sportsArray = root.getJSONArray("sport");
// now get the first element:
JSONObject firstSport = sportsArray.getJSONObject(0);
// and so on
String name = firstSport.getString("name"); // basketball
int id = firstSport.getInt("id"); // 40
JSONArray leaguesArray = firstSport.getJSONArray("leagues");

// and so on, you can process leaguesArrays similarily

Cela devrait fonctionner (n'hésitez pas à vous plaindre d'erreurs de compilation s'il y en a)

9
kiruwka

Vos données JSON sont un objet (elles commencent par une accolade). Dans la couche interne suivante, il y a un seul tableau (à la clé "sports"):

String jsonString = readURL("//my URL is here");
JSONObject result = JSONObject(jsonString);
JSONArray sports = result.getJSONArray("sports");
JSONObject sport = sport.getJSONObject(0);
System.out.println(sport.getString("name"));

J'aurais peut-être utilisé une autre bibliothèque JSON que vous.

2
Codo

JSON signifie JavaScript Object Notation.

Les objets dans les javascripts ne sont que des conteneurs et peuvent être représentés par des paires clé-valeur. Veuillez trouver ci-dessous des notations pour comprendre JSON.

Représenter des objets dans json: E.g. Étudiant

{"name" : "Robin", "rollnumber" : "1"}

Représenter le tableau dans json: E.g. Tableau d'étudiants

[{"name" : "Robin", "rollnumber" : "1"}, {"name" : "Mark", "rollnumber" : "2"}]

Vous pouvez en apprendre plus sur JSON à partir de diagrammes sur ce lien http://www.json.org/fatfree.html

Il existe différents moyens de convertir JSON en javaobject et javaobject en JSON: L’un d’eux est http://wiki.fasterxml.com/JacksonInFiveMinutes

0
BSS

Ajout de code détaillé ici avec les importations.

Si cela aide.

import org.json.JSONException;
import org.json.JSONObject;

public class extractingJSON {

    public static void main(String[] args) throws JSONException {
        // TODO Auto-generated method stub

        String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"},\"arrArray\":[{\"a\":\"1\",\"b\":\"2\"}]}";
        JSONObject jsonObj = new JSONObject(jsonStr);
        String name = jsonObj.getString("name");
        System.out.println(name);

        String first = jsonObj.getJSONObject("arr").getString("a");
        System.out.println(first);

        first = jsonObj.getJSONArray("arrArray").getJSONObject(0).getString("a");
        System.out.println(first);



    }


}
0
user3251882