JSON Support in NCache

NCache provides JSON support, a structured, human-readable, lightweight syntax for parsing, and data sharing. 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.

NCache supports JSON through:

JSON API in NCache

NCache allows you to add and retrieve cache data in the JSON format. 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. The following paragraphs explain these classes and their usage 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 to 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 to the cache.

var product = FetchProductFromDB("1001");
string jsonString = @$"{{ 
			""ProductID"" : ""{product.ProductID}"",
			""ProductName"" : ""{product.ProductName}"",
			""Category"" : ""{product.Category}"",
			""UnitsAvailable"" : ""{product.UnitsAvailable}""
			}}";
JsonObject jsonObject = new JsonObject(jsonString, "Alachisoft.NCache.Sample.Product");
string key = "Product:" + product.ProductID;

// Inserting object in cache
cache.Insert(key, jsonObject);
Product product = Product.fetchProductFromDB("Product:1001");
String jsonString = "{\"ProductID\":\"" + product.getProductID() + "\"," +
		    "\"ProductName\":\"" + product.getProductName() + "\"," +
		    "\"Category\":\"" + product.getCategory() + "\"," +
		    "\"UnitsAvailable\":" + product.getUnitsAvailable() +
		    "}";
JsonObject jsonObject = new JsonObject(jsonString, "com.alachisoft.ncache.sample.Product");
String key = "Product:" + product.getProductID();

// Inserting object in Cache
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 a custom object as a JSON object:

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

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 );
jsonArray.Add(jsonObject1);

var jsonObject2 = new JsonObject(jsonString2);
jsonArray.Add(jsonObject2);

string key = “JsonArrray:1001”;
cache.Insert(key, jsonArray);
var jsonArray = new JsonArray();
        //...
var jsonObject1 = new JsonObject(jsonString1, "com.alachisoft.ncache.sample.Product");
jsonArray.add(jsonObject1);
var jsonObject2 = new JsonObject(jsonString2, "com.alachisoft.ncache.sample.Product");
jsonArray.add(jsonObject2);

String key = "JsonArray:1001";

// Inserting JsonArray in Cache
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 the cache:

// Retrieve JsonArray from cache
string key = "JsonArray:1001";
JsonArray jsonArray = cache.Get<JsonArray>(key)

// Retrieve the value of the specified index
JsonValueBase value = jsonArray[2];
// Retrieve JSONArray from cache
String key = "JsonArray:1001";
JsonArray jsonArray = cache.get(key, JsonArray.class);

// Retrieve the value of the specified index
JsonValueBase value = jsonArray.getItem(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;
	//...
}
var enumerator = cache.asJsonIterator();
while (enumerator.hasNext())
{
	Entry entry = (Entry) enumerator.next();
	JsonValueBase valueBase =  (JsonValueBase) entry.getValue();
	//...
 }

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 based on its type.

Product product = FetchProductFromDB();
string jsonString = @$"{{ ""ProductID"" : ""{product.ProductID}"", ""ProductName"" : ""{product.ProductName}"", ""Price"" : {product.Price} }}";

JsonObject jsonObject = new JsonObject(jsonString, "Alachisoft.NCache.Sample.Product");
string key = "Product:" + product.ProductID;

cache.Insert(key, jsonObject);
Product product = Product.fetchProductFromDB("Product:1001");

String jsonString = "{\"productID\":\"" + product.getProductID() + "\", \"productName\" : \""+ product.getProductName() + "\", \"price\":\"" + product.getPrice() + "\"}";

JsonObject jsonObject = new JsonObject(jsonString,"com.alachisoft.ncache.sample.Product" );
String key = "Product:" +product.getProductID();
cache.insert(key, jsonObject);

Query JSON Data in Cache

Once you have indexed JSON data based on its type, you can perform SQL-like queries to fetch or delete the data from the cache. For more information on how to use all these searchable attributes while querying JSON data, refer to our documentation on Query JSON Data.

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);

 // QueryResult contains all the keys and metadata of result
 if (queryResult.FieldCount > 0) {
            while (queryResult.Read()) {
                // Perform operation according to your logic
            }
        }
else
{
	// No data
}
String query = "Select * FROM Alachisoft.NCache.Runtime.JSON.JsonObject WHERE Discount = ?";
QueryCommand queryCommand = new QueryCommand(query);
queryCommand.getParameters().put("Discount", 0.5);

var queryResult = cache.getSearchService().executeReader(queryCommand);
if (queryResult.getFieldCount() > 0) {
      while (queryResult.read()) {
      // Perform operation according to your logic
      }
}
else {
            // No data
        }

Sync JSON Data with Database

When storing data in the cache, NCache allows you to ensure 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 removes data from the cache if it is updated in the database. Learn more about Cache Data Dependency on Database from our documentation.
  • Expiration: You can add time-based expiration on your JSON data so that your cache is synchronized with the database. For more details, refer to our documentation on Data Expiration Strategies in Cache.
  • Events: NCache provides event notifications that are triggered when any registered operation is performed on your JSON serialized cache or JSON data. For more details, refer to our documentation on Event Notifications in Cache.
  • Data Source Providers: NCache allows persisting JSON data to the master data source and fetches data directly from the source if it is not found in the cache. Refer to our documentation on Data Source Providers for Cache to get detailed help on these providers.
  • Cache Startup Loader: JSON data can be automatically added to the cache when the cache starts using the Cache Startup Loader. For more details, 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 a 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 as shown below:

Product product = new Product();
product.Name = "Pizza";
product.Expiry = new DateTime(2020, 3, 28);
product.Sizes = new string[] { "Large", "Medium" };
Product product = new Product();
product.setName("Pizza");
product.setExpiry(new Date(2020, 3, 28));
product.setSizes(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 fully automated requiring 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.