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:
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:
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.
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.
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);
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);
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.
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).
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);
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 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.
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);
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
}
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.
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.
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.
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.