Using JSON Array as Cache Data
Note
This feature is available in NCache Enterprise and Professional editions.
JsonArray represents JArray
in JSON standards in NCache’s domain mapping arrays or list like collections in NCache’s domain to JArray
according to JSON conventions. JsonArray
is quite similar to JsonObject
, with the difference of JsonObject
being a key, value pair whereas JsonArray
being a collection.
The values added in JsonArray
can either be JsonValue
, JsonObject
, JsonNull
or even another JsonArray
; provided it is not adding itself to itself. Furthermore, you can update and add values in JsonArray
at specified indices using the indexer property. Providing value at a non-existing positive index will add at the specified index and all values from the last existing index to the new index will be JsonNull
.
If a value is already present at the specific index, the new value overwrites existing value. Moreover you can also remove values from an array by specifying the values using the Remove method.
Pre-Requisites
- Include the following namespace in your application:
Alachisoft.NCache.Client
Alachisoft.NCache.Runtime.JSON
Alachisoft.NCache.Runtime.Exceptions
- Cache must be JSON Serialized through NCache Web Manager.
- The application must be connected to cache before performing the operation.
- Cache must be running.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Get JsonArray from Json String
Similar to JsonObject
, JsonArray
also provides an overload where a JSON data string is passed containing a JsonArray
and the instance of the JsonArray
is populated as a result. In case of an invalid string; ArgumentException
is thrown.
Below is an example which populates an instance of a JsonArray
by passing a json data string.
try
{
// 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
}
catch (ArgumentException ae)
{
// Invalid JSON string passed
}
Create a JsonArray
You can create a JsonArray
and then add values in it. The Add method lets you add instances of JsonObject
, JsonValue
, JsonNull
or JsonArray
. It is important to note that a JsonArray
cannot add itself to itself. This form of relation is not allowed at any nested level i.e., a JsonArray
‘A’ cannot add a JsonObject
‘B’ that contains ‘A’ as an attribute and so on.
The following example creates an JsonArray
and add values in it.
try
{
// Pre-Condition: Cache is already connected
// 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";
// Insert the array in the cache with the key
cache.Insert(key, jsonArray);
// JsonArray is added in the cache successfully
}
catch(OperationFailedException ex)
{
if (ex.ErrorCode == NCacheErrorCodes.ATTRIBUTE_ALREADY_EXISTS)
{
// An attribute already exists with the same name
}
else if (ex.ErrorCode == NCacheErrorCodes.REFERENCE_TO_SELF)
{
// No object can contain a reference to itself
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add Value at a Particular Index
JsonArray
allows you to add JSON values at specified indices via the indexer. The idea is that if an item already exists at the specified index, it will be overwritten. If the item is being assigned at a non-existing positive index, the item will be added at the specified index and all the values between the last index and the new index will be JsonNull
. Note that in order to add a value at a certain index, you have to explicitly specify JsonValue
class for primitive types.
The following example adds a value to the fifth index of the array. Where the last value of the array was at the third index. So the values between the second and the sixth index will be JsonNull
.
try
{
// Pre-Condition: Cache is already connected
// 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";
// Insert the array in the cache with the key
cache.Insert(key, array);
}
catch(OperationFailedException ex)
{
if (ex.ErrorCode == NCacheErrorCodes.ATTRIBUTE_ALREADY_EXISTS)
{
// An attribute already exists with the same name
}
else if (ex.ErrorCode == NCacheErrorCodes.REFERENCE_TO_SELF)
{
// No object can contain a reference to itself
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Retrieve a JsonArray
You can get a JsonArray using the Get
method. You can retrieve a whole JsonArray using this method. Given below is an example showing how to retrieve a JsonArray created previously.
try
{
// Pre-Condition: Cache is already connected
// 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);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Retrieve Value at a Particular Index
This value returned is of JsonValueBase
type. In order to make use of it, you have to determine the right type of JSON value to which it is to be cast in order to use it. Providing a non-existent index to get the value, will throw an Index out of bound
exception.
The following example adds values to the array and then remove them by specifying the index.
try
{
// Pre-Condition: Cache is already connected
// 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;
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Remove Value from a JsonArray
You can remove a value from an array by specifying the value in the Remove method. This method returns a Boolean
flag that can be used to determine whether the item was removed or not. You can specify the value placed at the specific index and not the index in order to remove the value from the array. Re-insert with the updated array with the removed value in the cache. You cannot remove a value at a particular index by any method. However, you can set a value at a particular index as JsonNull
.
It is important to understand that remove works on data and not references. This means when removing an item with a similar item (i.e. they both contain exactly the same data) existing in the JsonArray
, the item first encountered will be removed always even if you provide the same reference that was used to add the item into JsonArray
.
The following example removes the value from the array previously created using the Remove method and then re-inserts the array in the cache.
try
{
// Pre-Condition: Cache is already connected
// 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);
// Re-insert the array in the cache with the value removed
cache.Insert(key, array);
// array is re-inserted in the cache with the removed value
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Remove JsonNull from an Array
You can also remove JsonNull
from an array. As mentioned in section “Remove Value from a JsonArray”, remove works on data and not references. Therefore, the first JsonNull
encountered will be removed from JsonArray
.
The following example will remove one null value from an array using the Remove method.
try
{
// Pre-Condition: Cache is already connected
// 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());
// Re-insert the array in the cache with the value removed
cache.Insert(key, array);
// array is re-inserted in the cache with the removed value
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Additional Resources
NCache provides sample application for Cache Data as JSON at:
- GitHub
- Shipped with NCache: *%NCHOME%\samples\dotnet\BasicOperationsWithJSON
See Also
Overview
Using JsonValue in Cache
Using JsonObject in Cache
Cache Serialization Format