Using JSON Object as Cache Data
Note
This feature is available in NCache Enterprise and Professional editions.
JsonObject is a class that represents JObject in JSON standards in NCache's domain. It is a container of unordered name/value pair where name is the string representation of the name of the whole attribute. The Value can either be JsonValue
which is a derived class from JsonValueBase
as well as JsonArray
. It can be a value of any primitive data type, listed below:
- Numeric types
- Boolean
- DateTime
NCache provides you with an ease of adding or retrieving JsonObjects
in/from the cache. In order to add data in cache as JSON, the objects need to be created according to the JSON standards provided by NCache. JsonObject is added in the cache against a unique key. This key will be used to perform further operations on the cache.
When retrieving cache data as JSON, the data of any custom class can be retrieved as a JsonObject
. This is highly beneficial at the user end as it lets the user add data of any custom class and get it as JSON.
Let us get a closer look at all the aspects of JsonObject
regarding NCache.
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 JsonObject from Json string
You can get a JsonObject
by passing a string containing the JsonObject
. It will parse the string and populate the instance of the JsonObject
containing the data in the string. If the string does not contain a valid jsonObject
; an ArgumentException
is thrown.
However if the datatype is not known; there is a static Parse()
method which returns the JsonValueBase
with the datatype of the provided data in the string.
The example below shows a string that contains a jsonObject
and returns an instance of the jsonObject
.
try
{
// Pre-Condition: Cache is JSON serialized
// The data provided in the string is a JsonObject
string jsonString = "{ 'ProductID' : 1001, 'ProductName' : 'Chai', 'Category': 'Beverages', 'UnitPrice' : 500, 'UnitsInStock' : 2000 }";
// Populate an instance of the JsonObject by passing the string
var jsonObject = new JsonObject(jsonString);
// Use the retrieved JsonObject for further operations
}
catch (ArgumentException ae)
{
// Invalid JSON string passed
}
The following example parses a string containing Json data with unknown datatype. The string is parsed to get the JsonDataType.
try
{
// Pre-Condition: Cache is JSON serialized
// Get the data from the provided Json file
string jsonString = System.IO.File.ReadAllText(@"d:\test.json");
// Parse the jsonString to get the JsonValueBase
var jsonValueBase = JsonValueBase.Parse(jsonString);
// Check the datatype of the jsonValueBase
switch (jsonValueBase.DataType)
{
case JsonDataType.Null:
var jsonNull = jsonValueBase as JsonNull;
// Use 'jsonNull' accordingly...
break;
case JsonDataType.Object:
var jsonObject = jsonValueBase as JsonObject;
// Use 'jsonObject' accordingly...
break;
case JsonDataType.Array:
var jsonArray = jsonValueBase as JsonArray;
// Use 'jsonArray' accordingly...
break;
default:
var jsonValue = jsonValueBase as JsonValue;
// Use 'jsonValue' accordingly...
break;
}
}
catch (ArgumentException ae)
{
// Invalid JSON string passed
}
Add JsonObject to Cache
When adding a JsonObject
to cache, you need to create a JsonObject
. After creating an object, you can add attributes of the specific object. Attributes are added using the AddAttribute method where you have to specify an attribute name and a value as JsonValue or JsonValueBase. Attribute name is case sensitive and cannot be redundant and in case of redundant attributes, exception is thrown.
Warning
- An attribute cannot contain a reference to the object itself. If done so, an exception is thrown.
- An attribute cannot have
null
value.
The example below creates a JsonObject
product along with the attributes and then adds it to the cache using the Insert method.
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 unique key for the object
string key = $"Product:{product.ProductID}";
// Create a new JSON object and set attributes
// string values need 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 object in the cache with the key
cache.Insert(key, jsonProduct);
// JsonObject will successfully be added to the cache
}
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 JsonArray to a JsonObject
You can add a JsonArray to a JsonObject
as an attribute of the JsonObject
. JsonArray
is a collection of JsonValues
, JsonObjects
or even other JsonArrays
. For more detail on JsonArray
please refer to the JsonArray section.
The following example adds a JsonArray
to the JsonObject
product as an attribute of the object using the Insert method.
{
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 unique key for the object
string key = $"Product:{product.ProductID}";
// Create a new JSON object and set attributes
// string values need 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);
// Create a new array containing the supplierIDs
var supplierArray = new JsonArray();
supplierArray.Add(1);
supplierArray.Add(2);
supplierArray.Add(6);
// Add this array as an attribute of the product object
jsonProduct.AddAttribute("SupplierIDs", supplierArray);
// Insert the object in the cache with the key
cache.Insert(key, jsonProduct);
}
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 Attributes of the JsonObject
You can also retrieve the attributes of a JsonObject
using the GetAttributeNames or GetAttributeValues method. The GetAttributeNames
method lets the user retrieve the names of the attributes of the JsonObject
in the form of a collection of strings whereas the GetAttributeValue
method retrieves the object of the JSON value against the provided attribute name.
Using GetAttributeNames()
The following example retrieves the names of the attributes of a JsonObject
product in the form of an ICollection
of strings.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// A JsonObject `product` has been created beforehand with various attributes
// Get the attribute names of the object
// and enumerate them in a collection of string
var attributeNames = jsonProduct.GetAttributeNames();
foreach (var attribute in attributeNames)
{
// Perform operations accordingly
}
}
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
}
Using GetAttributeValue()
The following example returns the value of the attribute ProductID in the form of an object.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// A JsonObject `product` has been created beforehand with various attributes
// Returns the value of the attribute "ProductID"
JsonValueBase value = product.GetAttributeValue("ProductID");
if (value != null)
{
// The object with the value is retrieved
}
else
{
// No such attribute exists
}
}
catch(OperationFailedException ex)
{
if (ex.ErrorCode == NCacheErrorCodes.ATTRIBUTE_ALREADY_EXISTS)
{
// An attribute already exists with the same name
}
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 Custom Object as JsonObject
NCache lets you retrieve a custom object in the form of a JsonObject
. The custom object is retrieved in the form of a JSON string having the data of the custom class.
The following example retrieves the data of a custom object in the form of a JSON string using the Get Method.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Get Product from database against given ProductID
Product product = FetchProductFromDB(1001);
// Generate a unique key for this product
string key = $"product.ProductID";
// Add the object with the key specified to the cache
cache.Insert(key, product);
// Retrieve the added object against the specified key
var retrievedItem = cache.Get<JsonObject>(key);
if(retrievedItem != null)
{
// Perform operations according to business logic
}
else
{
// No such item exists
}
}
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 JsonObject as Custom Object
You can also add a JsonObject
to the cache and retrieve it as a custom object. The properties of the custom class must be the same as the attributes of the JsonObject
by name and value.
Note
- The attributes of the
JsonObject
MUST be same as the properties of the custom class. - The cache being used MUST be Json Serialized.
The following example shows how to retrieve a JsonObject
as custom object.
try
{
// Pre-Condition: Cache has already been connected
// Cache is JSON serialized
// Create a new JsonObject with the following attributes in the string
string jsonString = "{'ProductID' : 1001, 'ProductName' : 'Coke', 'Category' : 'Beverages', 'UnitPrice' : 50, 'UnitsInStock' : 500 }";
// Retrieve the JsonObject from the string
JsonObject product = new JsonObject(jsonString);
// Create a unique key for this object
string key = "ProductID:1001";
// Insert JsonObject in the cache
cache.Insert(key, product);
// Get the JsonObject as a custom object
object retrievedItem = cache.Get<Product>(key);
if (retrievedItem != null)
{
// Perform operations according to business logic
}
else
{
// No such item exists
}
}
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.
Remove Attribute from JsonObject
You can also remove a particular attribute from an instance of a JsonObject
. This is done using the RemoveAttribute method which on providing with the attribute name, removes the attribute along with the value of the attribute. The success of removal can be identified via a flag returned by the RemoveAttribute call. A value of true indicates that the attribute was removed and vice versa. The only reason an attribute will not be removed is that the attribute does not exist. You will have to re-insert the item in the cache after removing the attribute from the object
The following example removes the attribute UnitPrice from the JsonObject
jsonProduct and then re-inserts the object in the cache.
try
{
// Pre-condition: Cache is already connected
// Cache is JSON serialized
// A JsonObject `product` is added in the cache with various attributes
// Specify the cache key
string key = "Product:1001";
// Retrieve the JsonObject
var jsonProduct = cache.Get<JsonObject>(key);
// Remove the attribute UnitPrice from the JsonObject
bool result = jsonProduct.RemoveAttribute("UnitPrice");
if (result == true)
{
// Attribute is successfully removed
}
else
{
// Wrong attribute name provided
}
// Re-insert the item in the cache with the removed attribute
cache.Insert(key, jsonProduct);
}
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 JsonArray in Cache
Cache Serialization Format