Recherche…


Syntaxe

  • Object : un objet est un ensemble non ordonné de paires nom / valeur. Un objet commence par {(accolade gauche) et se termine par} (accolade droite). Chaque nom est suivi de: (deux points) et les paires nom / valeur sont séparées par (virgule).

  • Tableau : un tableau est une collection ordonnée de valeurs. Un tableau commence par [(crochet gauche) et se termine par] (crochet droit). Les valeurs sont séparées par, (virgule).

  • Valeur : Une valeur peut être une chaîne entre guillemets, ou un nombre, ou vrai ou faux ou null, ou un objet ou un tableau. Ces structures peuvent être imbriquées.

  • Chaîne : une chaîne est une séquence de zéro ou plusieurs caractères Unicode, entourés de guillemets doubles, à l'aide de barres obliques inverses. Un caractère est représenté par une chaîne de caractères unique. Une chaîne ressemble beaucoup à une chaîne C ou Java.

  • Number : Un nombre ressemble beaucoup à un numéro C ou Java, sauf que les formats octal et hexadécimal ne sont pas utilisés.

Remarques

Cette rubrique concerne l'utilisation du package org.json inclus dans le SDK Android.

Analyser un objet JSON simple

Considérez la chaîne JSON suivante:

{
  "title": "test",
  "content": "Hello World!!!",
  "year": 2016,
  "names" : [
        "Hannah",
        "David",
        "Steve"
   ]
} 

Cet objet JSON peut être analysé à l'aide du code suivant:

try {
    // create a new instance from a string
    JSONObject jsonObject = new JSONObject(jsonAsString);
    String title = jsonObject.getString("title");
    String content = jsonObject.getString("content");
    int year = jsonObject.getInt("year");
    JSONArray names = jsonObject.getJSONArray("names"); //for an array of String objects
} catch (JSONException e) {
    Log.w(TAG,"Could not parse JSON. Error: " + e.getMessage());
}

Voici un autre exemple avec un JSONArray imbriqué dans JSONObject:

{
    "books":[
      {
        "title":"Android JSON Parsing",
        "times_sold":186
      }
    ]
}

Cela peut être analysé avec le code suivant:

JSONObject root = new JSONObject(booksJson);
JSONArray booksArray = root.getJSONArray("books");
JSONObject firstBook = booksArray.getJSONObject(0);
String title = firstBook.getString("title");
int timesSold = firstBook.getInt("times_sold");

Créer un objet JSON simple

Créez l'objet JSONObject à l'aide du constructeur vide et ajoutez des champs à l'aide de la méthode put() , qui est surchargée pour pouvoir être utilisée avec différents types:

try {
    // Create a new instance of a JSONObject
    final JSONObject object = new JSONObject();
    
    // With put you can add a name/value pair to the JSONObject
    object.put("name", "test");
    object.put("content", "Hello World!!!1");
    object.put("year", 2016);
    object.put("value", 3.23);
    object.put("member", true);
    object.put("null_value", JSONObject.NULL);

    // Calling toString() on the JSONObject returns the JSON in string format.
    final String json = object.toString();
    
} catch (JSONException e) {
    Log.e(TAG, "Failed to create JSONObject", e);
}

La chaîne JSON résultante ressemble à ceci:

{  
   "name":"test",
   "content":"Hello World!!!1",
   "year":2016,
   "value":3.23,
   "member":true,
   "null_value":null
}

Ajouter JSONArray à JSONObject

// Create a new instance of a JSONArray
JSONArray array = new JSONArray();

// With put() you can add a value to the array.
array.put("ASDF");
array.put("QWERTY");

// Create a new instance of a JSONObject
JSONObject obj = new JSONObject();

try {
    // Add the JSONArray to the JSONObject
    obj.put("the_array", array);
} catch (JSONException e) {
    e.printStackTrace();
}

String json = obj.toString();

La chaîne JSON résultante ressemble à ceci:

{  
   "the_array":[  
      "ASDF",
      "QWERTY"
   ]
}

Créez une chaîne JSON avec une valeur nulle.

Si vous devez produire une chaîne JSON avec une valeur null comme ceci:

{  
   "name":null
}

Ensuite, vous devez utiliser la constante spéciale JSONObject.NULL .

Exemple de fonctionnement:

jsonObject.put("name", JSONObject.NULL);

Travailler avec une chaîne vide lors de l'analyse syntaxique de json

{
    "some_string": null,
    "ather_string": "something"
}

Si nous allons utiliser cette façon:

JSONObject json = new JSONObject(jsonStr);
String someString = json.optString("some_string");

Nous aurons une sortie:

someString = "null";

Nous devons donc fournir cette solution de contournement:

/**
 * According to http://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null
 * we need to provide a workaround to opt string from json that can be null.
 * <strong></strong>
 */
public static String optNullableString(JSONObject jsonObject, String key) {
    return optNullableString(jsonObject, key, "");
}

/**
 * According to http://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null
 * we need to provide a workaround to opt string from json that can be null.
 * <strong></strong>
 */
public static String optNullableString(JSONObject jsonObject, String key, String fallback) {
    if (jsonObject.isNull(key)) {
        return fallback;
    } else {
        return jsonObject.optString(key, fallback);
    }
}

Et puis appelez:

JSONObject json = new JSONObject(jsonStr);
String someString = optNullableString(json, "some_string");
String someString2 = optNullableString(json, "some_string", "");

Et nous aurons la sortie comme prévu:

someString = null; //not "null"
someString2 = "";

Utiliser JsonReader pour lire JSON depuis un flux

JsonReader lit une valeur codée JSON sous forme de flux de jetons.

   public List<Message> readJsonStream(InputStream in) throws IOException {
     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
     try {
       return readMessagesArray(reader);
     } finally {
       reader.close();
     }
   }

   public List<Message> readMessagesArray(JsonReader reader) throws IOException {
     List<Message> messages = new ArrayList<Message>();

     reader.beginArray();
     while (reader.hasNext()) {
       messages.add(readMessage(reader));
     }
     reader.endArray();
     return messages;
   }

   public Message readMessage(JsonReader reader) throws IOException {
     long id = -1;
     String text = null;
     User user = null;
     List<Double> geo = null;

     reader.beginObject();
     while (reader.hasNext()) {
       String name = reader.nextName();
       if (name.equals("id")) {
         id = reader.nextLong();
       } else if (name.equals("text")) {
         text = reader.nextString();
       } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
         geo = readDoublesArray(reader);
       } else if (name.equals("user")) {
         user = readUser(reader);
       } else {
         reader.skipValue();
       }
     }
     reader.endObject();
     return new Message(id, text, user, geo);
   }

   public List<Double> readDoublesArray(JsonReader reader) throws IOException {
     List<Double> doubles = new ArrayList<Double>();

     reader.beginArray();
     while (reader.hasNext()) {
       doubles.add(reader.nextDouble());
     }
     reader.endArray();
     return doubles;
   }

   public User readUser(JsonReader reader) throws IOException {
     String username = null;
     int followersCount = -1;

     reader.beginObject();
     while (reader.hasNext()) {
       String name = reader.nextName();
       if (name.equals("name")) {
         username = reader.nextString();
       } else if (name.equals("followers_count")) {
         followersCount = reader.nextInt();
       } else {
         reader.skipValue();
       }
     }
     reader.endObject();
     return new User(username, followersCount);
   }

Créer un objet JSON imbriqué

Pour produire un objet JSON imbriqué, vous devez simplement ajouter un objet JSON à un autre:

JSONObject mainObject = new JSONObject();            // Host object
JSONObject requestObject = new JSONObject();         // Included object

try {
    requestObject.put("lastname", lastname);
    requestObject.put("phone", phone);
    requestObject.put("latitude", lat);
    requestObject.put("longitude", lon);
    requestObject.put("theme", theme);
    requestObject.put("text", message);

    mainObject.put("claim", requestObject);
} catch (JSONException e) {
    return "JSON Error";
}

mainObject contient mainObject une clé appelée claim avec la totalité de requestObject comme valeur.

Gestion de la clé dynamique pour la réponse JSON

Ceci est un exemple sur la façon de gérer la clé dynamique pour la réponse. Ici, A et B sont des clés dynamiques, cela peut être n'importe quoi

Réponse

{
  "response": [
    {
      "A": [
        {
          "name": "Tango"
        },
        {
          "name": "Ping"
        }
      ],
      "B": [
        {
          "name": "Jon"
        },
        {
          "name": "Mark"
        }
      ]
    }
  ]
}

Code Java

// ResponseData is raw string of response
JSONObject responseDataObj = new JSONObject(responseData);
JSONArray responseArray = responseDataObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
    // Nodes ArrayList<ArrayList<String>> declared globally
    nodes = new ArrayList<ArrayList<String>>();
    JSONObject obj = responseArray.getJSONObject(i);
    Iterator keys = obj.keys();
    while(keys.hasNext()) {
       // Loop to get the dynamic key
       String currentDynamicKey = (String)keys.next();
       // Get the value of the dynamic key
       JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey);
       int jsonArraySize = currentDynamicValue.length();
       if(jsonArraySize > 0) {
           for (int ii = 0; ii < jsonArraySize; ii++) {
                // NameList ArrayList<String> declared globally
                nameList = new ArrayList<String>();
               if(ii == 0) {
                JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
                String name = nameObj.getString("name");
                System.out.print("Name = " + name);
                // Store name in an array list
                nameList.add(name);
              }
           }                    
       }
     nodes.add(nameList);
    }
}

Vérifier l'existence de champs sur JSON

Parfois, il est utile de vérifier si un champ est présent ou absent sur votre JSON pour éviter une JSONException sur votre code.

Pour cela, utilisez la JSONObject#has(String) ou la méthode, comme dans l'exemple suivant:

Exemple de JSON

{
   "name":"James"
}

Code Java

String jsonStr = " { \"name\":\"James\" }";
JSONObject json = new JSONObject(jsonStr);
// Check if the field "name" is present
String name, surname;

// This will be true, since the field "name" is present on our JSON.
if (json.has("name")) {
    name = json.getString("name");
}
else {
    name = "John";
}
// This will be false, since our JSON doesn't have the field "surname".
if (json.has("surname")) {
    surname = json.getString("surname");
}
else {
    surname = "Doe";
}

// Here name == "James" and surname == "Doe".

Mise à jour des éléments dans le JSON

échantillon json pour mettre à jour

 {
 "student":{"name":"Rahul", "lastname":"sharma"},
 "marks":{"maths":"88"}
 }

Pour mettre à jour la valeur des éléments dans json, nous devons affecter la valeur et la mise à jour.

try {
    // Create a new instance of a JSONObject
    final JSONObject object = new JSONObject(jsonString);
    
    JSONObject studentJSON = object.getJSONObject("student");
    studentJSON.put("name","Kumar");
  
     object.remove("student");

     object.put("student",studentJSON);

    // Calling toString() on the JSONObject returns the JSON in string format.
    final String json = object.toString();
    
} catch (JSONException e) {
    Log.e(TAG, "Failed to create JSONObject", e);
}

valeur actualisée

 {
 "student":{"name":"Kumar", "lastname":"sharma"},
 "marks":{"maths":"88"}
 }


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow