Buscar..


Sintaxis

  • Objeto : un objeto es un conjunto desordenado de pares nombre / valor. Un objeto comienza con {(corchete izquierdo) y termina con} (tirante derecho). Cada nombre va seguido de: (dos puntos) y los pares nombre / valor están separados por, (coma).

  • Array : una matriz es una colección ordenada de valores. Una matriz comienza con [(corchete izquierdo) y termina con] (corchete derecho). Los valores están separados por, (coma).

  • Valor : Un valor puede ser una cadena entre comillas dobles, o un número, o verdadero o falso o nulo, o un objeto o una matriz. Estas estructuras pueden ser anidadas.

  • Cadena : una cadena es una secuencia de cero o más caracteres Unicode, envueltos en comillas dobles, utilizando escapes de barra invertida. Un carácter se representa como una sola cadena de caracteres. Una cadena es muy parecida a una cadena C o Java.

  • Número : un número es muy parecido a un número C o Java, excepto que no se utilizan los formatos octal y hexadecimal.

Observaciones

Este tema trata sobre el uso del paquete org.json que se incluye en el SDK de Android.

Parse simple objeto JSON

Considera la siguiente cadena JSON:

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

Este objeto JSON se puede analizar utilizando el siguiente código:

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());
}

Aquí hay otro ejemplo con un JSONArray anidado dentro de JSONObject:

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

Esto se puede analizar con el siguiente código:

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");

Creando un objeto JSON simple

Cree el JSONObject usando el constructor vacío y agregue campos usando el método put() , que está sobrecargado para que se pueda usar con diferentes tipos:

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 cadena JSON resultante se ve así:

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

Añadir JSONArray a 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 cadena JSON resultante se ve así:

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

Crear una cadena JSON con valor nulo.

Si necesita producir una cadena JSON con un valor null como este:

{  
   "name":null
}

Entonces tienes que usar la constante especial JSONObject.NULL .

Ejemplo de funcionamiento:

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

Trabajando con una cadena nula al analizar json

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

Si vamos a utilizar de esta manera:

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

Tendremos salida:

someString = "null";

Así que tenemos que proporcionar esta solución:

/**
 * 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);
    }
}

Y luego llamar:

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

Y tendremos salida como esperábamos:

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

Uso de JsonReader para leer JSON desde una secuencia

JsonReader lee un valor codificado JSON como un flujo de tokens.

   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);
   }

Crear objeto JSON anidado

Para producir un objeto JSON anidado, necesita simplemente agregar un objeto JSON a otro:

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";
}

Ahora mainObject contiene una clave llamada claim con todo el requestObject como un valor.

Manejo de clave dinámica para respuesta JSON

Este es un ejemplo de cómo manejar la clave dinámica para la respuesta. Aquí A y B son claves dinámicas puede ser cualquier cosa.

Respuesta

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

Código 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);
    }
}

Compruebe la existencia de campos en JSON

A veces es útil verificar si un campo está presente o ausente en su JSON para evitar alguna JSONException en su código.

Para lograrlo, use el JSONObject#has(String) o el método, como en el siguiente ejemplo:

Muestra JSON

{
   "name":"James"
}

Código 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".

Actualizando los elementos en el JSON.

muestra json para actualizar

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

Para actualizar el valor de los elementos en el json debemos asignar el valor y actualizar.

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);
}

valor actualizado

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


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow