JSON Support in NCache

NCache provides you with JSON support that is a structured, human-readable, lightweight syntax for parsing, and sharing of data. The major ease provided by NCache to you through Cache Data as JSON is the flexibility of retrieving data of any custom class in your cache as JSON. Moreover, data can be added as JSON and retrieved and parsed as a custom class.

JSON support in NCache is divided into two main sections:

JSON API in NCache

NCache allows you to add and retrieve cache data in the form of JSON. NCache supports multiple JSON structures to insert and fetch JSON data efficiently. These structures are:

  • JSON Object
  • JSON Array

Both these structures are derived from an abstract class by the name JsonValueBase. Let us look at what these classes are and how they are used in NCache to store and retrieve data.

JSON Object

JsonObject represents JObject in JSON standards in the NCache domain. JsonObject holds unordered name-value pairs and is added in the cache against a unique key which is later used to perform cache operations. To retrieve cache data as JSON, NCache allows any custom class to be retrieved as a JsonObject.

Add JsonObject in Cache

You can insert a JsonObject to the cache in the following way. This example shows how to populate a JsonObject with a serialized string and add it in the cache.

var product = GetProductFromDB();
string jsonString = $@"{{
                        'ProductID': { product.ProductID},
                        'ProductName': '{product.ProductName}',
                        'Category': '{product.Category}',
                        'UnitsAvailable' : { product.UnitsAvailable}
JsonObject jsonObject = new JsonObject(jsonString);
cache.Insert(key, jsonObject);

Retrieve JsonObject from Cache

NCache allows you to retrieve a cached custom object in the form of a JsonObject. This returns a JSON string containing the data of your custom class. NCache also allows you to cache a JsonObject and fetch it as a custom object using the same Get API. Here is an example of how to retrieve custom object as a JSON object:

var jsonObject = cache.Get<JsonObject>(key);

JSON Array

JsonArray in NCache is the representation of JArray in JSON standards. JsonArray is an ordered list of values. These values can be string, number, boolean, object, or another array.

Add JsonArray in Cache

You can add JsonObject or even another JsonArray in a JsonArray. NCache uses the indexer property to add and update values in a JsonArray. You can create a JsonArray using a JsonObject in the following way:

var jsonArray = new JsonArray();
var jsonObject1 = new JsonObject(jsonString1);

var jsonObject2 = new JsonObject(jsonString2);

cache.Insert(key, jsonArray);

In NCache, you can also add JSON data at specified indices in a JsonArray. If an item already exists at the specified index, it is overwritten. If the specified index does not exist, the item is added at that index and all the values between the last populated index and the new index are set to JsonNull (null in JSON standards).

Retrieve JsonArray or its Particular Index Value

NCache allows you to fetch the entire JsonArray from the cache or retrieve the value from a particular index on the JsonArray. Once retrieved, you can enumerate it or perform index-based operations on the data. This is how you can fetch a JsonArray or a particular value from cache:

// Retrieve JSONArray from cache
JsonArray jsonArray = cache.Get<JsonArray>(key);

// Retrieve the value of the specified index
JsonValueBase value = jsonArray[2];

JSON Enumerator

NCache also allows you to take JsonEnumerator on Cache to fetch all JSON Objects and JSON Arrays in the following way:

var enumerator = (IDictionaryEnumerator)_cache.GetJsonEnumerator();
while (enumerator.MoveNext())
    DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
    JsonValueBase valueBase = (JsonValueBase)entry.Value;

NCache Features Supported with JSON

NCache is a feature-rich distributed cache that provides many features to ease you into storing and retrieving your data. Just like for native and custom objects, NCache also supports such features for JSON type data.

Index JSON Data in Cache

NCache allows you to index JSON data if the added data has searchable attributes associated with it. These searchable attributes are Groups, Tags, and Named Tags.

  • JSON Data with Groups: Groups logically partition or group your JSON data under a similar category. You can perform various operations on a group of items by querying on the group data. Refer to our documentation on Add JSON Data with Groups for more detail.
  • JSON Data with Tags: Tags are string-based identifiers that add useful information to the cached JSON data. Using tags, you can query the JSON data more efficiently. For more detail, refer to our documentation on Add JSON Data with Tags.
  • JSON Data with Named Tags: Named Tags provide a higher level of tagging where the tags can have specific names and types. These tags help you query your cached JSON data efficiently. Refer to Add JSON Data with Named Tags for more detail.

The following example shows how to add Named Tags to a JsonArray and then cache it.

var item = new CacheItem(jsonObject);
var productNamedTag = new NamedTagsDictionary();

productNamedTag.Add("Discount", 0.5);
item.NamedTags = productNamedTag;
item.Group = "Eatables";
item.Tags = new Tag("Processed Food");

cache.Insert(key, item);

Query JSON Data in Cache

Once you have indexed JSON data in cache using groups, tags, or named tags, you can perform SQL-like queries to fetch or delete the data from the cache. Keeping in view the previous example of named tags, you can query for the data indexed with the “Discount” named tag like this:

string query = "Select * FROM Alachisoft.NCache.Runtime.JSON.JsonObject WHERE Discount = ?";
QueryCommand queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("Discount", 0.5);

var queryResult = cache.SearchService.ExecuteReader(queryCommand);

For more information on how to use all these searchable attributes while querying JSON data, refer to our documentation on Query JSON Data.

Sync JSON Data with Database

When storing data in the cache, NCache allows you to make sure that the data you are working with is not stale. To ensure this, NCache has provided the following features that keep your cache and database synchronized.

  • Cache Dependencies: NCache supports cache dependencies on the JSON data that remove data from the cache if it is updated in the database. Know more about Cache Data Dependency on Database from our documentation.
  • Expiration: You can add time-based expiration on your JSON data to keep your cache in-sync with the database. Refer to our documentation on Data Expiration Strategies in Cache to know more.
  • Events: NCache provides event notifications that are triggered when any registered operation is performed on your JSON serialized cache or JSON data. To know more, refer to our documentation on Event Notifications in Cache.
  • Data Source Providers: NCache allows persisting JSON data to the master data source and fetching data directly from the source if it is not found in the cache. Refer to our guide on Data Source Providers for Cache to get detailed help on these providers.
  • Cache Startup Loader: JSON data can be automatically added in the cache when cache starts using the Cache Startup Loader. For more detail, refer to our documentation on Cache Startup Loader.

JSON Serialization of .NET and Java Objects

In JSON serialization, the objects are converted into their JSON equivalent when serialized and then converted back into their custom objects at the time of deserialization.

NCache provides JSON serialization support for both .NET and Java objects.

  • You can store a custom object in a Json Serialized cache from a .NET client and fetch the data through a Java client as JsonObject.
  • You can store a custom object in Json Serialized cache from a Java client and retrieve it through a .NET client as a JsonObject.
  • You can also store a JSON object in a non-Json Serialized cache from a .NET client and retrieve it via a Java client as a JsonObject and vice versa.

Let us consider you have the following Product attributes in .NET. You can store this object in the cache as a custom object, the way it has been shown below:

Product product = new Product();
product.Name = "Pizza";
product.Expiry = new DateTime(2020, 3, 28);
product.Sizes = new string[] { "Large", "Medium" };

Or, serialize this data using JSON serialization. When you opt for JSON serialization, this data will be serialized to the following JSON string:

   "Name": "Pizza",
   "Expiry": "2020-3-28T00:00:00",
   "Sizes": ["Large", "Medium"]

JSON serialization is memory efficient, portable, and is fully automated that requires no code change for you to implement it. NCache also allows you to specify which attributes you want to serialize and which to leave as is.

What to Do Next?

Review NCache Features
Download NCache
Request a Personalized LIVE Demo

Signup for monthly email newsletter to get latest updates.

© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.