• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

Using JSON Object as Cache Data

JSON is a lightweight data-interchange format used to represent structured data as name/value pairs. Microsoft’s Windows.Data.Json.JsonObject provides a dictionary-like JSON container that can be used to create, modify, parse, and stringify JSON data in a .NET application.

With NCache, a JSON object can be used as application-side JSON data. Before adding it to the cache, convert the JSON object into its string representation by using Stringify(). The JSON string is then stored in NCache against a unique cache key. This key is used to retrieve, update, or remove the cached JSON data. After retrieving the cached value, get it as a string and reconstruct the JSON object by using JsonObject.Parse() or JsonObject.TryParse(). Once reconstructed, you can access JSON properties using typed APIs such as GetNamedString(), GetNamedNumber(), GetNamedBoolean(), and GetNamedObject().

Windows.Data.Json.JsonObject supports standard JSON value types such as:

  • String
  • Number
  • Boolean
  • Object
  • Array
  • Null
Important

Windows.Data.Json.JsonObject is an application-side JSON object and is not the same as NCache’s JSON object model. For best compatibility, store it in NCache as a JSON string and reconstruct it after retrieval.

Prerequisites

  • .NET
  • Install the Alachisoft.NCache.SDK NuGet package in your application.
  • Make sure your application can access Windows Runtime APIs because Windows.Data.Json.JsonObject belongs to the Windows.Data.Json namespace.
  • Include the following namespaces in your application:
    • Alachisoft.NCache.Client
    • Alachisoft.NCache.Runtime.Exceptions
    • Windows.Data.Json
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • The value being added to NCache must be serializable.
  • For NCache API details, refer to: ICache, Insert, Get, Remove, CacheManager, and GetCache.
Note

In this approach, Windows.Data.Json.JsonObject is used as an application-side JSON object. Before storing it in NCache, convert it to a JSON string.

Since the cached value is a string, NCache does not automatically index individual JSON properties. Adding a regular JSON property such as "Type" only stores type information as part of the JSON data; it does not register the item as an NCache JSON-indexed type. If indexed queries over object fields are required, store a strongly typed object and configure NCache indexes for that type.

How to Add JSON Object to Cache

When adding JSON data to NCache, create a JSON object in the client application and store it against a unique cache key. The key is later used to retrieve, update, or remove the cached data. In .NET, create a Windows.Data.Json.JsonObject, populate it with the required properties, convert it to a JSON string by using Stringify(), and add the string to NCache using the Insert method.

Properties are added or updated by using the SetNamedValue() method, where you specify the property name and its value as an IJsonValue. The property name is case-sensitive. Use JsonValue.CreateStringValue(), JsonValue.CreateNumberValue(), JsonValue.CreateBooleanValue(), or another compatible JSON value type depending on the data being stored.

The following example creates a JSON object for a customer, converts it to a JSON string, and adds it to NCache using the Insert method.

  • .NET
try
{
    // Pre-Condition: Cache is already connected

    // Obtain an instance of the cache using the provided cache name
    ICache cache = CacheManager.GetCache(cacheName);

    // Assume customer is an instance of the Customer class

    // Create a unique key
    string customerKey = "Customer:ALFKI";

    // Create a new JSON object and set properties
    JsonObject jsonCustomer = new JsonObject();

    jsonCustomer.SetNamedValue("CustomerID", JsonValue.CreateStringValue(customer.CustomerID));
    jsonCustomer.SetNamedValue("ContactName", JsonValue.CreateStringValue(customer.ContactName));
    jsonCustomer.SetNamedValue("CompanyName", JsonValue.CreateStringValue(customer.CompanyName));

    // Convert the JSON object to its string representation
    string jsonCustomerString = jsonCustomer.Stringify();

    // Add the JSON string to the cache
    cache.Insert(customerKey, jsonCustomerString);

    Console.WriteLine($"Customer with key '{customerKey}' has been added.");
    Console.WriteLine(jsonCustomerString);
}
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
}
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 JSON Object to Cache from JSON String

You can also create a JSON object by parsing an existing JSON string. Use JsonObject.Parse() when the JSON string is known to be valid, or JsonObject.TryParse() when the JSON string may be invalid. After the JSON string is parsed, store its string representation in NCache against a unique cache key.

  • .NET
...

// Create a unique key
string customerKey = "Customer:ALFKI";

// JSON string representing customer data
string jsonString = @"{
    ""CustomerID"": ""ALFKI"",
    ""ContactName"": ""Maria Anders"",
    ""CompanyName"": ""Alfreds Futterkiste""
}";

// Parse the JSON string into a JsonObject
if (JsonObject.TryParse(jsonString, out JsonObject jsonCustomer))
{
    // Store the JSON representation in NCache
    cache.Insert(customerKey, jsonCustomer.Stringify());

    Console.WriteLine($"Customer with key '{customerKey}' has been added.");
}
else
{
    Console.WriteLine("The provided JSON string is not valid.");
}
...

How to Retrieve JSON Object from Cache

To retrieve a JSON object from NCache, get the cached value as a string using the cache key. Since the Windows.Data.Json.JsonObject was stored as a JSON string, parse the retrieved string back into a JsonObject before accessing its properties.

The following example retrieves a cached JSON string for a customer, parses it into a JsonObject, and reads selected customer properties.

  • .NET
...

// Create a unique key
string customerKey = "Customer:ALFKI";

// Retrieve the JSON string from cache
string cachedJson = cache.Get<string>(customerKey);

Console.WriteLine("Retrieved from cache:");
Console.WriteLine(cachedJson);

if (!string.IsNullOrEmpty(cachedJson) &&
    JsonObject.TryParse(cachedJson, out JsonObject retrievedCustomer))
{
    string customerId = retrievedCustomer.GetNamedString("CustomerID", string.Empty);
    string contactName = retrievedCustomer.GetNamedString("ContactName", string.Empty);
    string companyName = retrievedCustomer.GetNamedString("CompanyName", string.Empty);

    Console.WriteLine("Parsed JSON object successfully.");
    Console.WriteLine($"Customer ID: {customerId}");
    Console.WriteLine($"Contact Name: {contactName}");
    Console.WriteLine($"Company Name: {companyName}");
}
else
{
    Console.WriteLine("Cached JSON could not be retrieved or parsed.");
}
...

How to Retrieve JSON Data as a Custom Object

When a Windows.Data.Json.JsonObject is stored in NCache as a JSON string, it is retrieved from the cache as a string. To use the cached JSON data as a custom object, parse the retrieved string into a JsonObject and map the JSON properties to your custom class.

The recommended approach is:

  1. Retrieve the JSON string from NCache.
  2. Parse it into a Windows.Data.Json.JsonObject.
  3. Map the JSON properties to your custom object.

The following example retrieves customer JSON data from the cache and maps it to a Customer object.

  • .NET
...

// Create a unique key
string customerKey = "Customer:ALFKI";

// Retrieve the JSON string from cache
string jsonForCustomerMapping = cache.Get<string>(customerKey);

if (!string.IsNullOrEmpty(jsonForCustomerMapping) &&
    JsonObject.TryParse(jsonForCustomerMapping, out JsonObject jsonForCustomer))
{
    Customer mappedCustomer = new Customer
    {
        CustomerID = jsonForCustomer.GetNamedString("CustomerID", string.Empty),
        ContactName = jsonForCustomer.GetNamedString("ContactName", string.Empty),
        CompanyName = jsonForCustomer.GetNamedString("CompanyName", string.Empty)
    };

    // Perform operations according to business logic
    Console.WriteLine("Mapped customer object:");
    Console.WriteLine(mappedCustomer);
    Console.WriteLine($"Company Name: {mappedCustomer.CompanyName}");
}
else
{
    Console.WriteLine("Could not map JSON to Customer object.");
}
...

How to Update JSON Object in Cache

NCache lets you update cached data by retrieving the item, modifying it, and inserting it again with the same key. When using Windows.Data.Json.JsonObject, retrieve the cached JSON data as a string, parse it into a JSON object, update the required properties, convert it back to a string by using Stringify(), and insert it back into the cache.

The following example updates the CompanyName property of a cached customer and adds an UpdatedBy property to the JSON data.

  • .NET
...

// Create a unique key
string customerKey = "Customer:ALFKI";

// Retrieve the JSON string from cache
string jsonToUpdate = cache.Get<string>(customerKey);

if (!string.IsNullOrEmpty(jsonToUpdate) &&
    JsonObject.TryParse(jsonToUpdate, out JsonObject jsonCustomerToUpdate))
{
    // Update an existing property
    jsonCustomerToUpdate.SetNamedValue(
        "CompanyName",
        JsonValue.CreateStringValue("Alachisoft")
    );

    // Add a new property
    jsonCustomerToUpdate.SetNamedValue(
        "UpdatedBy",
        JsonValue.CreateStringValue("Windows.Data.Json")
    );

    // Insert with the same key to update the existing cached value
    cache.Insert(customerKey, jsonCustomerToUpdate.Stringify());

    Console.WriteLine($"Customer with key '{customerKey}' has been updated.");
    Console.WriteLine(jsonCustomerToUpdate.Stringify());
}
else
{
    Console.WriteLine("Could not update because cached JSON was missing or invalid.");
}
...
Note

SetNamedValue() inserts the property if it does not already exist and updates it if it does. Therefore, reinserting the JSON string with the same cache key updates the cached JSON data.

How to Remove JSON Object from Cache

Since the JSON object is stored in NCache as a JSON string, it can be removed from the cache the same way as any other cached item. Specify the cache key and call the Remove method.

The following example removes the cached JSON string from NCache.

  • .NET
...

// Specify the customer key
string customerKey = "Customer:ALFKI";

// Remove the cached JSON string from NCache
cache.Remove(customerKey);

Console.WriteLine("Cached item removed.");

...
Note

If you need to inspect the JSON data before removing it, retrieve it using Get before calling Remove.

Additional Resources

NCache provides sample application for Cache Data as JSON on GitHub.

See Also

Cache Operations

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • 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 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top