• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Try Free
Show / Hide Table of Contents

Using JSON Object as Cache Data

Note

This feature is available in NCache Enterprise and Professional editions.

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

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

  • .NET/.NET Core
  • Java
  • Scala
  • 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.
  • 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: Cache, JsonObject, JsonValueBase, insert, get, addAttribute, JsonValue, CacheItem, parse.
  • 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: Cache, JsonObject, JsonValueBase.
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 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 Product along with attributes and then adds it to the cache using the Insert method.

  • .NET/.NET Core
  • Java
  • Scala
// 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);
}
// Cache is JSON serialized
// Specify unique key
String key = "Product:" + product.getProductID();

// Create a new JSON object and set attributes
// string values need to be added with JsonValue
var jsonProduct = new JsonObject();
jsonProduct.addAttribute("ProductID", new JsonValue(product.getProductID()));
jsonProduct.addAttribute("ProductName", new JsonValue(product.getProductName()));
jsonProduct.addAttribute("Category", new JsonValue(product.getCategory()));
jsonProduct.addAttribute("UnitPrice", new JsonValue(product.getUnitPrice()));
jsonProduct.addAttribute("UnitsInStock", new JsonValue(product.getUnitsInStock()));

// Create a new CacheItem for product and then insert
CacheItem cacheItem = new CacheItem(jsonProduct);

// Add object in the cache with the key
cache.insert(key, cacheItem);
val product = fetchProductFromDB(1001)

// Cache is JSON serialized
// Specify unique key
val key = "Product:" + product.getProductId

// Create a new JSON object and set attributes
// string values need to be added with JsonValue
val jsonProduct = new JsonObject
jsonProduct.addAttribute("ProductID", new JsonValue(product.getProductId))
jsonProduct.addAttribute("ProductName", new JsonValue(product.getProductName))
jsonProduct.addAttribute("Category", new JsonValue(product.getCategory))
jsonProduct.addAttribute("UnitPrice", new JsonValue(product.getPrice))
jsonProduct.addAttribute("UnitsInStock", new JsonValue(product.getUnitsAvailable))

// Create a new CacheItem for product and then insert
val cacheItem = new CacheItem(jsonProduct)

// Add object in the cache with the key
cache.insert(key, cacheItem)
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 Manager, 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.

  • .NET/.NET Core
// 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.

  • .NET/.NET Core
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.

  • .NET/.NET Core
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 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.

  • .NET/.NET Core
  • Java
  • Scala
// Get Customer from database against given CustomerID
Customer customer = FetchCustomerFromDB(1001);

// Generate a unique key for this customer
string key = $"customer.CustomerID";

// Add the object with the key specified to the cache
cache.Insert(key, customer);

// 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
}
// Generate a unique key for this product
String key = "Product:1001";

// Create a new CacheItem for product and then insert
var cacheItem = new CacheItem(product);

// Add the object with the key specified to the cache
cache.insert(key, cacheItem);

// Retrieve the added object against the specified key

var retrievedItem = cache.get(key,JsonObject.class);

if(retrievedItem != null)
{
    // Perform operations according to business logic
}
else
{
    // No such item exists
}
val product = fetchProductFromDB(1001)

// Generate a unique key for this product
val key = "Product:1001"

// Create a new CacheItem for product and then insert
val cacheItem = new CacheItem(product)

// Add the object with the key specified to the cache
cache.insert(key, cacheItem)

// Retrieve the added object against the specified key
val retrievedItem = cache.get(key, classOf[JsonObject])

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 custom object as a JsonObject, the cache should be JSON serialized.

The following example shows how to retrieve a JsonObject as custom object.

  • .NET/.NET Core
  • Java
  • Scala
// 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
}
// 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
JsonValueBase jsonValueBase = JsonObject.parse(jsonString);
JsonObject product = null;
if(jsonValueBase instanceof JsonObject)
{
    product = (JsonObject) jsonValueBase;
}

// Create a unique key for this object
String key = "ProductID:1001";

// Create a new CacheItem for product and then insert
var cacheItem = new CacheItem(product);

// Insert JsonObject in the cache
cache.insert(key, cacheItem);

// Get the JsonObject as a custom object
var retrievedItem = cache.get(key,Product.class);
if(retrievedItem != null)
{
    // Perform operations according to business logic
}
else
{
    // No such item exists
}
// Create a new JsonObject with the following attributes in the string
val jsonString = "{'ProductID' : 1001, 'ProductName' : 'Coke', 'Category' : 'Beverages', 'UnitPrice' : 50, 'UnitsInStock' : 500 }"

// Retrieve the JsonObject from the string
val jsonValueBase = JsonObject(jsonString, "Data.Product")
var product: JsonObject = null
if (jsonValueBase.isInstanceOf[JsonObject]) product = jsonValueBase.asInstanceOf[JsonObject]

// Create a unique key for this object
val key = "ProductID:1001"

// Create a new CacheItem for product and then insert
val cacheItem = new CacheItem(product)

// Insert JsonObject in the cache
cache.insert(key, cacheItem)

// Get the JsonObject as a custom object
val retrievedItem = cache.get(key, classOf[Product])
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

JSon Data types and Properties Overview
Cache Serialization Format

Back to top Copyright © 2017 Alachisoft