Try Playground
Show / Hide Table of Contents

Using JSON Object as Cache Data [Deprecated]

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

  • .NET
  • Java
  • 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.
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.

  • .NET
  • Java
// 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.");
}
// Obtain an instance of the cache using the provided cache name
Cache cache = CacheManager.getCache(cacheName);

// Get customer from database against the given customer ID
Customer customer = CustomerDataset.fetchCustomerFromDB("Customer:ALFKI");

// Create a unique key for the object
String key = customer.getCustomerID();

// Create a new com.alachisoft.ncache.sample.JSON object and set attributes
JsonObject jsonCustomer = new JsonObject();
jsonCustomer.addAttribute("CustomerID", new JsonValue(customer.getCustomerID()));
jsonCustomer.addAttribute("ContactName", new JsonValue(customer.getContactName()));
jsonCustomer.addAttribute("CompanyName", new JsonValue(customer.getCompanytName()));
jsonCustomer.addAttribute("Phone", new JsonValue(customer.getPhone()));
jsonCustomer.addAttribute("Address", new JsonValue(customer.getAddress()));

// Create a new CacheItem
CacheItem item = new CacheItem(jsonCustomer);

// Add CacheItem in the cache with the value
cache.insert(key, item);

System.out.println("Customer added to cache: " + key);
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.

  • .NET
  • Java
// 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);
// Get customer from database against the given customer ID
Customer customer = CustomerDataset.fetchCustomerFromDB("Customer:ALFKI");

// Create a unique key for the object
String key = customer.getCustomerID();

// Create a new object and set attributes
JsonObject jsonCustomer = new JsonObject();
jsonCustomer.addAttribute("Type", new JsonValue(Customer.class));
jsonCustomer.addAttribute("CustomerID", new JsonValue(customer.getCustomerID()));
jsonCustomer.addAttribute("ContactName", new JsonValue(customer.getContactName()));
jsonCustomer.addAttribute("ConmpanyName", new JsonValue(customer.getCompanyName()));
jsonCustomer.addAttribute("Phone", new JsonValue(customer.getPhone()));
jsonCustomer.addAttribute("Address", new JsonValue(customer.getAddress()));

// Create a new CacheItem
CacheItem item = new CacheItem(jsonCustomer);

// Add CacheItem in the cache with the value
cache.insert(key, item);

System.out.println("Customer added to cache: " + key);
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
  • Java
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");
}
// Create a unique key for the object
String key = "Customer:ALFKI";

// Get the JsonObject from the cache
JsonObject jsonCustomer = (JsonObject) cache.get(key, JsonObject.class);

if (jsonCustomer != null)
{
    // Modify the JsonObject
    jsonCustomer.removeAttribute("CompanyName");
    jsonCustomer.addAttribute("CompanyName", new JsonValue("Alachisoft"));

    // Update the cache with the modified JsonObject
    cache.insert(key, jsonCustomer);

    System.out.println("Customer updated in cache: " + key);
}

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
  • Java
// 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");
}
// Specify the customer key
String customerKey = "Customer:ALFKI";

// JsonObject to be returned
JsonObject customerJObject = cache.remove(customerKey, JsonObject.class);
if (customerJObject != null) {
    System.out.println("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.

  • .NET
  • Java
// 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
}
// Create a unique key for this object
String key = "Customer:ALFKI";

JsonObject customer = cache.get(key, JsonObject.class);

if (customer != null)
{
    // Perform operations according to business logic
    System.out.println("Customer retrieved from cache: " + customer);
}
else
{
    // No such item exists
    System.out.println("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.

  • .NET
  • Java
// 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
}
JsonObject customer = new JsonObject();
customer.addAttribute("contactName", new JsonValue("Daniel Smith"));
customer.addAttribute("customerID", new JsonValue("Customer:BTMKJ"));
customer.addAttribute("phone", new JsonValue("+1-341-11-944"));

// Create a unique key for this object
String key = "Customer:ALFKI";

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

// Get the JsonObject as a custom object
Customer retrievedItem = cache.get(key, Customer.class);

if (retrievedItem != null)
{
    // Perform operations according to business logic
    System.out.println("Customer retrieved from cache: " + retrievedItem);
}
else
{
    // No such item exists
    System.out.println("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.

In This Article
  • Prerequisites for Using JSON Object as Cache Data
  • Add JsonObject to Cache
    • Add JsonObject to Cache with Type Name
  • Update JsonObject in Cache
  • Remove JsonObject from Cache
  • Retrieve Custom Object as JsonObject
  • Retrieve JsonObject as Custom Object
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top