Using Primitive Types as JSON Value in Cache
Note
This feature is available in NCache Enterprise and Professional editions.
JsonValue is a class derived from JsonValueBase and represents a value which can be of any primitive types in JSON standard. That includes the types listed below:
- Number (Signed/Unsigned)
- String
- DateTime
- Boolean
You can add value of any primitive type including others such as string
, DateTime
or decimal
in .NET as JsonValue
in the cache. JsonValue
cannot be instantiated via the new operator. However if you want to create a JsonValue
, you will have to use the implicit operators overloaded in JsonValue
. All of these operators are defined as implicit in nature except for the string
operator which is defined as explicit and needs to be cast as JsonValue
.
Additionally you can also store a DateTime
value in a JsonValue
.
It is important to understand that there is no concept of DateTime
in JSON standards. And so, DateTime
is stored as a string
when assigned to JsonValue
. The DateTime
instance is converted to string
using "yyyy-MM-ddTHH:mm:ss.FFFFFFFK"
format and "en-US"
culture info by default. If you wish to deal with a custom format for DateTime
, you will have to convert it to string using your own format and format provider.
These values can be added in the cache against a key and then retrieved or removed as per requirement. You can also store values in JsonValueBase
and then identify their type using the JsonDataType
property.
You can get the data as any supported type provided by JsonValue
as long as the operation is valid. In order to get a value as string
data type, JsonValue
contains ToStringValue
to get a value as string and ToDateTime
for DateTime
along with the choice of providing the data formats.
Pre-Requisites
- Include the following namespace in your application:
Alachisoft.NCache.Client
Alachisoft.NCache.Runtime.JSON
Alachisoft.NCache.Runtime.Exceptions
- Cache must be JSON Serialized through NCache Web Manager.
- Cache must be running.
- The application must be connected to cache before performing the operation.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add and Get String as JsonValue
In order to add a string
as a JsonValue
, it needs to be cast as the operation is defined as explicit in nature.
The following example adds a string JsonValue
to cache against a key using the Insert method and then retrieves the string value added against the specified key.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);
// Add a string value as JsonValue
var jsonValue = (JsonValue)product.ProductName;
// Create a unique key for this
string key = $"Product:{product.ProductID}";
// Add the string value in cache against the specified key
cache.Insert(key, jsonValue);
// String value is added against the key
// Retrieve the inserted value of the string against the key
var retrievedValue = cache.Get<JsonValue>(key);
// The value against the key is retrieved successfully
}
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
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add and Get Number as JsonValue
You can add a number as JsonValue
to the cache. The following example adds an integer as well as a float value to the cache.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);
// Add an integer value as JSON;
JsonValue jsonInt = product.ProductID;
JsonValue jsonFloat = product.UnitPrice;
// Specify unique keys
string keyInt = $"Product:{product.ProductID}";
string keyFloat = $"Product:{product.ProductID}.UnitPrice";
// Add these values in cache against the key specified
cache.Insert(keyInt, jsonInt);
cache.Insert(keyFloat, jsonFloat);
// Retrieve the values added against the specified keys
var retrievedValue = cache.Get<JsonValue>(keyInt);
// The value has been retrieved successfully
}
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
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add DateTime as JsonValue
You can add DateTime
as JsonValue
. Since there is no concept of DateTime
in JSON standards, it is therefore added as a string.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Add DateTime value as JSON
DateTime dateTimeValue = DateTime.Now;
JsonValue jsonValue = dateTimeValue;
// Create a unique key
string key = "JsonDataTime";
// Add the value of JSON DateTime in the cache
cache.Insert(key, jsonValue);
}
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
}
You can also add DateTime
according to your own provided format but it will have to be constructed to a string
and added as a string
thus. Along with the format, it is recommended to also provide your format provider (usually in the form of CultureInfo
) to specify the region. This makes the retrieval of DateTime
more accurate on the user end.
The following example adds Datetime
as a JsonValue
according to the provided format.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Specify a custom DateTime format
string customDateTimeFormat = "yyyy.MM.dd_HHmm_ss.ff";
// Add DateTime value as JSON
// along with the custom datetime format
DateTime dateTimeValue = DateTime.Now;
JsonValue jsonValue = (JsonValue)dateTimeValue.ToString(customDateTimeFormat, CultureInfo.CurrentCulture);
// Create a unique key
string key = "JsonDateTime";
// Add the value of JSON DateTime in the cache
cache.Insert(key, jsonValue);
}
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
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add Boolean as JsonValue
You can also add boolean
as a JsonValue
. The value can either be true
or false
.
The following example adds false as a boolean
JsonValue
in cache against a specific key.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Create a new boolean value as JsonValue
Product product = FetchProductFromDB(1001);
JsonValue jsonValue = product.IsContinued;
// Create a unique key
string key = $"Product:{product.ProductID}";
// Add the boolean value in the cache against the key
cache.Insert(key, jsonValue);
// Boolean value for the product availability is successfully added
}
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
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Retrieve a String as Other Data Types
JsonValue
lets you add value in a specific data format and then retrieve the value as a different data type as long as the operation is valid. For example you can add an Integer
and get the value as Float
using the ToFloat()
method.
Note
- Unless 'value' is either 'True' or 'False', you cannot get value as
boolean
and an exception will be thrown on doing so.
The following example adds a number in the form of a string
and gets the value as an integer
.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Create a JsonValue as string
string value = "10";
JsonValue jsonValue = (JsonValue)value;
// Create a unique key
string key = "StringValue";
// Add the value in the cache against the key
cache.Insert(key, value);
// Retrieve the value against the specified key
var retrievedValue = cache.Get<JsonValue>(key);
// Convert the retrieved value to integer
retrievedValue.ToInt32();
// The output will be 10
}
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
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Retrieve a Number as Other Data Types
Similar to string
, you can retrieve numbers as other data types such as boolean
or string
.
The following example adds an integer in the cache as JsonValue
and retrieve it as a string
.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Add an integer as JsonValue
int value = 1000;
JsonValue jsonValue = value;
// Create a unique key
string key = "JsonValue";
// Add the value in the cache against the key
cache.Insert(key, jsonValue);
// Retrieve the value as a string
var retrievedValue = cache.Get<JsonValue>(key);
// Convert the json value to string
retrievedValue.ToStringValue();
// Convert the json value to double
retrievedValue.ToDouble();
// The value according to your logic will be retrieved
}
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
In order to get the complete list of retrieval methods for JsonValue
please refer to the JsonValue section in API documentation.
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Special Considerations while Using JsonValue
The maximum value a
JsonValue
can hold is Unsigned Long.max (18446744073709551615) and the minimum value is Signed Long.min (9223372036854775808). Any value greater or smaller than the limit values will lose precision.Boolean
when get as a number has its value 1 for true and has its value 0 for false. You can also get theboolean
value as string. However, you cannot retrieveboolean
asDateTime
as it results in an exception.
Boolean | Number | String | DateTime |
---|---|---|---|
True | 1 | “True” | Not allowed |
False | 0 | “False” | Not allowed |
The example below depicts the behavior of a boolean
JsonValue
when used as DateTime.
try
{
bool value = true;
JsonValue json = value;
json.ToDateTime();
}
catch(Exception ex)
{
// Handle exception accordingly
}
An exception occurs saying String was not recognized as a valid DateTime
on performing the specified function.
Boolean
string can be used as string. Getting it as number orDateTime
results in an exception. Make sure that the value ofboolean
string isTrue
orFalse
with the capital first letters.
BooleanString | Number | String | DateTime |
---|---|---|---|
“True” | Not allowed | “True” | Not allowed |
“False” | Not allowed | “False” | Not allowed |
The following example shows getting a boolean
string as an integer.
try
{
string boolStr = "true";
JsonValue json = (JsonValue)boolStr;
json.ToInt32();
}
catch(Exception ex)
{
// Handle Exception accordingly
}
An exception occurs saying Input string was not in a correct format
on performing the specified function.
- If a
DateTime
is get as any data type other thanDateTime
, an exception is thrown.
DateTime | Number | String | Boolean |
---|---|---|---|
Normal Format | Not allowed | DateTime in default string format | Not allowed |
Custom Format | Not allowed | DateTime in custom string format | Not allowed |
The following code example shows getting a DateTime
value as an integer.
try
{
JsonValue jsonDate = DateTime.Now;
jsonDate.ToInt32();
}
catch(Exception ex)
{
// Handle exception accordingly
}
An exception occurs saying Input string was not in a correct format
on performing the specified function.
The data structures
Float
,Decimal
andDouble
are always signed and cannot be unsigned. Signed numbers can be returned as signed numbers provided they exist within the limit.Any number returned as
boolean
will always be true. However, 0 will be returned as false asboolean
.
Number | Floating Number | Boolean | String | DateTime |
---|---|---|---|---|
Signed (Decimal, Float, Double are always signed) | Allowed | Number in string format | Not allowed | |
Unsigned | Allowed | Number in string format | Not allowed |
Floating Number | Number | Boolean | String | DateTime |
---|---|---|---|---|
Signed | Rounded to nearest value | Number in string format | Not allowed | |
Unsigned | Rounded to nearest value | Number in string format | Not allowed |
The following example shows the behavior of an integer, returned as boolean
.
try
{
int integer = 30;
JsonValue integerValue = integer;
bool boolVal = integerValue.ToBoolean();
}
catch(Exception ex)
{
// Handle exception accordingly
}
The output of the above example will be the value of boolVal as true
.
A string can only be returned as a string. Trying to get a string as any other data type results in an exception.
A string containing a numeric only can be get as a number so long as it remains in the number’s limits.
String | Number | DateTime | Boolean |
---|---|---|---|
String | Not allowed | Not allowed | Not allowed |
Number Formatted string e.g. “10” | Number e.g. 10 | Not allowed | Not allowed |
The following example shows the behavior of a string when retrieved as a number.
try
{
string value = "Product Details";
JsonValue stringValue = (JsonValue)value;
stringValue.ToInt64();
}
catch (Exception ex)
{
// Handle exception accordingly
}
An exception occurs saying Input string was not in a correct format
on performing the specified function.
Additional Resources
NCache provides sample application for Cache Data as JSON at:
- GitHub
- Shipped with NCache: *%NCHOME%\samples\dotnet\BasicOperationsWithJSON
See Also
Overview
Using JsonObject in Cache
Using JsonArray in Cache
Cache Serialization Format