Uso de JSON Array como datos de caché
Note
Esta función está disponible en NCache Empresa y Profesional.
JsonArray
representa JArray
en estándares JSON en NCachematrices de mapeo de dominios o listas como colecciones en NCacheel dominio de JArray
de acuerdo con las convenciones JSON. JsonArray
es bastante similar a JsonObject
, con la diferencia de JsonObject
siendo un par clave, valor mientras que JsonArray
siendo una colección.
Los valores agregados en JsonArray
puede ser JsonValue
, JsonObject
, JsonNull
o incluso otro JsonArray
; siempre que no se añada a sí mismo. Además, puede actualizar y agregar valores en JsonArray
en índices especificados utilizando la propiedad indexer. Proporcionar valor en un índice positivo inexistente se agregará en el índice especificado y todos los valores desde el último índice existente hasta el nuevo índice serán JsonNull
.
Si un valor ya está presente en el índice específico, el nuevo valor sobrescribe el valor existente. Además, también puede eliminar valores de una matriz especificando los valores usando el Eliminar método.
Requisitos previos
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página dada en Requisitos previos de la API del lado del cliente.
- Para obtener detalles de la API, consulte: Dolor, Artículo de caché, jsonmatriz, JsonObjeto, JsonValorBase, recuadro, Recibe, Eliminar, Agregar atributo.
Importante:
Para garantizar que la operación sea a prueba de fallas, se recomienda manejar cualquier posible excepción dentro de su aplicación, como se explica en Manejo de fallas.
Obtener JsonArray de Json String
Similar a JsonObject
, JsonArray
también proporciona una sobrecarga donde se pasa una cadena de datos JSON que contiene un JsonArray
y la instancia de la JsonArray
se llena como resultado. En caso de una cadena no válida; ArgumentException
es aventado.
A continuación se muestra un ejemplo que llena una instancia de un JsonArray
pasando una cadena de datos json.
// Precondition: Cache is already connected
// The data provided in the string is a JsonArray
string jsonString = " ['ProductIDs', { 'ProductID' : 1001 }, { 'ProductID' : 1002 }, { 'ProductID' : 1003 } ]";
// Populate an instance of the JsonArray by passing the string
var jsonArray = new JsonArray(jsonString);
// Use the retrieved JsonArray for further operations
Crear un JsonArray
Usted puede crear un JsonArray
y luego agregue valores en él. El método Add le permite agregar instancias de JsonObject
, JsonValue
, JsonNull
or JsonArray
. Es importante señalar que un JsonArray
no puede agregarse a sí mismo. Esta forma de relación no está permitida en ningún nivel anidado, es decir, un JsonArray
'A' no puede agregar un JsonObject
'B' que contiene 'A' como atributo y así sucesivamente.
El siguiente ejemplo crea un JsonArray
y agregar valores en él.
// Cache is JSON serialized
// Create a new JsonArray
var jsonArray = new JsonArray();
// Get top ten products from the data source
Product[] products = FetchTop10Products();
// Convert these products in JsonObjects
foreach (Product product in products)
{
// Create jsonObject and set its attributes
// ProductName is string so it needs to be added with JsonValue
var jsonProduct = new JsonObject();
jsonProduct.AddAttribute("ProductID", product.ProductID);
jsonProduct.AddAttribute("ProductName", (JsonValue)product.ProductName);
jsonProduct.AddAttribute("Category", (JsonValue)product.Category);
jsonProduct.AddAttribute("UnitPrice", product.UnitPrice);
jsonProduct.AddAttribute("UnitsInStock", product.UnitsInStock);
// Add jsonObjects to the jsonArray
jsonArray.Add(jsonProduct);
}
// Create a unique key for the array
string key = "Products";
// Create a new CacheItem for product and then insert
var cacheItem = new CacheItem(jsonArray);
// Insert the array in the cache with the key
cache.Insert(key, cacheItem);
Agregar valor en un índice particular
JsonArray
le permite agregar valores JSON en índices específicos a través del indexador. La idea es que si un elemento ya existe en el índice especificado, se sobrescribirá. Si el artículo se asigna a un índice positivo inexistente, el artículo se agregará al índice especificado y todos los valores entre el último índice y el nuevo índice serán JsonNull
. Tenga en cuenta que para agregar un valor en un índice determinado, debe especificar explícitamente JsonValue
clase para tipos primitivos.
El siguiente ejemplo agrega un valor al quinto índice de la matriz. Donde el último valor de la matriz estaba en el tercer índice. Entonces los valores entre el segundo y el sexto índice serán JsonNull
.
// Cache is JSON serialized
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);
// Create a new JSON object
// Set attributes of the object
var jsonProduct = new JsonObject();
jsonProduct.AddAttribute("ProductID", product.ProductID);
// ProductName is string so it needs to be added with JsonValue
jsonProduct.AddAttribute("ProductName", (JsonValue)product.ProductName);
jsonProduct.AddAttribute("Category", (JsonValue)product.Category);
jsonProduct.AddAttribute("UnitPrice", product.UnitPrice);
jsonProduct.AddAttribute("UnitsInStock", product.UnitsInStock);
// Create a new JsonArray
var array = new JsonArray();
// Add the items to the array
// The values at the index 3 and 4 will be JsonNull
array.Add((JsonValue)"ProductList");
array.Add(jsonProduct);
array[5] = (JsonValue)2.02;
array[6] = (JsonValue)new DateTime(2009, 10, 10);
// Create a unique key for the array
string key = "Products";
// Create a new CacheItem for product and then insert
var cacheItem = new CacheItem(array);
// Insert the array in the cache with the key
cache.Insert(key, cacheItem);
Recuperar un JsonArray
Puede obtener un JsonArray usando el Get
método. Puede recuperar un JsonArray completo con este método. A continuación se muestra un ejemplo que muestra cómo recuperar un JsonArray creado anteriormente.
// Cache is JSON serialized
// An array is already added in the cache with the values
// Specify the key of the array
string key = "Products";
// Retrieve the array from the cache with the help of the key
var array = cache.Get<JsonArray>(key);
Recuperar valor en un índice particular
Este valor devuelto es de JsonValueBase
tipo. Para utilizarlo, debe determinar el tipo correcto de valor JSON al que se va a convertir para usarlo. Proporcionar un índice inexistente para obtener el valor arrojará un Index out of bound
excepción.
El siguiente ejemplo agrega valores a la matriz y luego los elimina especificando el índice.
// Cache is JSON serialized
// Create a new JsonArray
var array = new JsonArray();
// Add values to the array
var prod = new JsonObject();
array.Add(prod);
array.Add(20);
array[10] = (JsonValue)new DateTime(2010, 10, 10);
// Retrieve the value of the specified index
JsonValueBase valueBase = array[10];
switch (valueBase.DataType)
{
case JsonDataType.Object:
// Use as JsonObject
break;
case JsonDataType.Array:
// Use as JsonArray
break;
case JsonDataType.Null:
// Use as JsonNull
break;
default:
JsonValue value = valueBase as JsonValue;
// Use value
break;
}
Eliminar valor de un JsonArray
Puede eliminar un valor de una matriz especificando el valor en el Eliminar método. Este método devuelve un Boolean
indicador que se puede utilizar para determinar si el elemento se eliminó o no. Puede especificar el valor colocado en el índice específico y no el índice para eliminar el valor de la matriz. Vuelva a insertar con la matriz actualizada con el valor eliminado en el caché. No puede eliminar un valor en un índice particular por ningún método. Sin embargo, puede establecer un valor en un índice particular como JsonNull
.
Es importante entender que eliminar funciona sobre datos y no sobre referencias. Esto significa que al eliminar un elemento con un elemento similar (es decir, ambos contienen exactamente los mismos datos) existente en el JsonArray
, el elemento encontrado por primera vez se eliminará siempre, incluso si proporciona la misma referencia que se utilizó para agregar el elemento en JsonArray
.
El siguiente ejemplo elimina el valor de la matriz creada previamente usando el Eliminar método y luego vuelve a insertar la matriz en el caché.
// Cache is JSON serialized
// An array is already added in the cache with the values
// Specify the key of the array
string key = "Products";
// Retrieve the array from the cache with the help of the key
var array = cache.Get<JsonArray>(key);
// Remove a product from the array
array.Remove(jsonProduct2);
// Create a new CacheItem for product and then insert
var cacheItem = new CacheItem(array);
// Re-insert the array in the cache with the value removed
cache.Insert(key, cacheItem);
Eliminar JsonNull de una matriz
También puedes eliminar JsonNull
de una matriz. Como se mencionó en la sección "Eliminar valor de un JsonArray", elimine trabajos sobre datos y no sobre referencias. Por lo tanto, la primera JsonNull
encontrado será eliminado de JsonArray
.
El siguiente ejemplo eliminará un valor nulo de una matriz usando el Eliminar método.
// Cache is JSON serialized
// An array is already added in the cache with the values
// Specify the key of the array
string key = "Products";
// Retrieve the array from the cache with the help of the key
var array = cache.Get<JsonArray>(key);
// Remove a product from the array
array.Remove(new JsonNull());
// Create a new CacheItem for product and then insert
var cacheItem = new CacheItem(array);
// Re-insert the array in the cache with the value removed
cache.Insert(key, cacheItem);
Recursos adicionales
NCache proporciona una aplicación de muestra para Cache Data como JSON en GitHub.
Vea también
.NETO: Alachisoft.NCache.Tiempo de ejecución.JSON espacio de nombres
Java: com.alachisoft.ncache.runtime.json espacio de nombres