Using JSON Object as Cache Data
The JsonObject
is a class that represents JObject in JSON standards in NCache's domain. It is a container of unordered name/value pair where the name is the string representation of the name of the whole attribute. It can be a value of any primitive data type, as listed below:
- Numeric types
- Boolean
- DateTime
Note
This feature is also available in NCache Professional.
NCache lets users add or retrieve JsonObjects
from the cache. To add data, the objects must abide by the JSON standards provided by NCache. The JsonObject
is added to the cache against a unique key. This key helps perform further operations on the cache.
When retrieving cache data as JSON, the data of any custom class can be retrieved as a JsonObject
, provided that the cache is JSON serialized. This approach is highly beneficial at the user end as it lets the user add data of any custom class and get it as a JSON object.
Prerequisites for Using JSON Object as Cache Data
- To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
- For API details, refer to: ICache, JsonObject, Insert, Get, AddAttribute, RemoveAttribute, CacheManager, GetCache, Add, JsonValue.
Note
If you have defined indexes, you must provide a type name to create a JSON object, as it won't be indexed without the type information.
Add JsonObject to Cache
When adding a JsonObject
to the cache, you must create a JsonObject
. After creating an object, you can add attributes of the specific object. Attributes are added to this object using the AddAttribute
method, where you must specify an attribute name and a value as JsonValue
or JsonValueBase
. The attribute name is case-sensitive and cannot be redundant. In case there are redundant attributes, an exception is thrown.
Alternatively, you can get a JsonObject
by passing a string containing the JsonObject
. It will parse the string and populate the JsonObject
instance containing the string data.
Warning
- An attribute cannot contain a reference to the object itself. If done so, an exception is thrown.
- An attribute cannot have a
null
value.
The example below creates a JsonObject
Customer along with attributes and then adds it to the cache using the Insert method.
// Obtain an instance of the cache using the provided cache name
ICache cache = CacheManager.GetCache(cacheName);
string customerKey = $"Customer:ALFKI";
Customer customer = cache.Get<Customer>(customerKey);
// Get customer from database if not found in cache
if (customer == null)
{
customer = HelperMethods.FetchCustomerFromDB("ALFKI");
// Create a new JSON object and set attributes
JsonObject jsonCustomer = new JsonObject();
jsonCustomer.AddAttribute("CustomerID", (JsonValue)customer.CustomerID);
jsonCustomer.AddAttribute("ContactName", (JsonValue)customer.ContactName);
jsonCustomer.AddAttribute("CompanyName", (JsonValue)customer.CompanyName);
jsonCustomer.AddAttribute("Phone", (JsonValue)customer.Phone);
jsonCustomer.AddAttribute("Address", (JsonValue)customer.Address);
cache.Add(customerKey, jsonCustomer);
Console.WriteLine($"Customer '{customer}' with key '{customerKey}' has been added.");
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add JsonObject to Cache with Type Name
If you have defined JSON indexes for querying and you've defined (such as Alachisoft.NCache.Customer) in the NCache Management Center, you will have to add data to the cache with the necessary type name, such as the attribute you require (e.g., CompanyName), as demonstrated in the code snippets below.
// Get customer from database against given customer ID
Customer customer = FetchCustomerFromDB(1001);
// Create a unique key for the object
string key = $"Customer:{customer.CustomerID}";
// Create a new JSON object and set attributes
// string values need to be added with JsonValue
var jsonCustomer = new JsonObject("Alachisoft.NCache.Customer");
jsonCustomer.AddAttribute("Type", customer.getType());
jsonCustomer.AddAttribute("CustomerID", customer.CustomerID);
jsonCustomer.AddAttribute("ContactName", (JsonValue)customer.ContactName);
jsonCustomer.AddAttribute("CompanyName", (JsonValue)customer.CompanyName);
jsonCustomer.AddAttribute("Phone", customer.Phone);
jsonCustomer.AddAttribute("Address", customer.Address);
// Create a new CacheItem
var item = new CacheItem(jsonCustomer);
// Add CacheItem in the cache with the value
cache.Insert(key, item);
Note
If you have defined indexes, you must provide a type name to query the JSON object, as it won't be possible without the type name. However, this is not necessary if you do not intend to query the JsonObject
.
Update JsonObject in Cache
NCache lets you add, update, fetch, and remove attributes from a JsonObject
already in the cache. For example, you can get a Customer stored as a JsonObject
and edit the company he works for (provided you mention the correct key) using the Insert API.
var jsonCustomer = cache.Get<JsonObject>(key);
if (jsonCustomer !=null)
{
jsonCustomer.RemoveAttribute("CompanyName");
jsonCustomer.AddAttribute("CompanyName", "Alachisoft");
Cache.Insert(key,jsonCustomer );
}
else
{
Console.WriteLine($"No such customer exists");
}
Remove JsonObject from Cache
NCache lets you remove a JsonObject
from the cache. For example, you can remove a Customer JsonObject
the same way as you remove any other cache item.
// Specify the customer key
string customerKey = $"Customer:ALFKI";
// JsonObject to be returned
JsonObject customerJObject = null;
bool isItemRemoved = cache.Remove(customerKey, out customerJObject);
if (isItemRemoved)
{
Console.WriteLine($"Customer with ID { customerJObject.GetAttributeValue('CustomerID') } has been removed");
}
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.
Note
To retrieve a custom object as a JsonObject
, the cache should be JSON serialized.
The following example retrieves the data of a custom object in the form of a JSON string using the Get Method.
// Create a unique key for this object
string key = $"customer.CustomerID";
// 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
}
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
To retrieve a custom object as a JsonObject
, the cache should be JSON serialized.
The following example shows how to retrieve a JsonObject
as a custom object.
// Create a new JsonObject with the following attributes in the string
string jsonString = $@"{{
""CustomerID"": ""1"",
""ContactName"": ""David Johnes"",
""CompanyName"": ""Lonesome Pine Restaurant"",
""Phone"": ""12345 - 6789"",
""Address"": ""Silicon Valley, Santa Clara, California""
}}";
// Retrieve the JsonObject from the string
JsonObject customer = new JsonObject(jsonString);
// Create a unique key for this object
string key = "CustomerID:1001";
// Insert JsonObject in the cache
cache.Insert(key, customer);
// Get the JsonObject as a custom object
object retrievedItem = cache.Get<Customer>(key);
if (retrievedItem != null)
{
// Perform operations according to business logic
}
else
{
// No such item exists
}
Additional Resources
NCache provides sample application for Cache Data as JSON on GitHub.
See Also
.NET: Alachisoft.NCache.Runtime.JSON namespace.
Java: com.alachisoft.ncache.runtime.json namespace.