• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Try Free
Show / Hide Table of Contents

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 ToStringValueto get a value as string and ToDateTime for DateTime along with the choice of providing the data formats.

Prerequisites

  • .NET/.NET Core
  • Java
  • Scala
  • To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
  • For API details refer to: ICache, CacheItem, JsonValue, JsonValueBase, Insert, Get.
  • To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
  • For API details refer to: Cache, JsonValue, CacheItem, JsonValueBase, insert, get.
  • To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
  • For API details refer to: Cache, CacheItem, JsonValue, JsonValueBase.

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.

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

    // 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
    string key = $"Product:{product.ProductID}";

    // Create a new CacheItem for product and then insert
    var cacheItem = new CacheItem(jsonValue);

    // Add the string value in cache against the specified key
    cache.Insert(key, cacheItem);
    // String value is added against the key

    // Retrieve the inserted value of the string against the key
    var retrievedValue = cache.Get<JsonValue>(key);

}
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
}
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
    JsonValue jsonValue = new JsonValue(product.getProductName());

    // Create a unique key
    String key = "JSONProduct:" + product.getProductID();

    // Create a new CacheItem for product and then insert
    CacheItem cacheItem = new CacheItem(jsonValue);

    // Add the string value in cache against the specified key
    cache.insert(key, cacheItem);

    // Retrieve the inserted value of the string against the key
    var retrievedValue = cache.get(key,JsonValue.class);

}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any generic exception like NullPointerException or IllegalArgumentException
}
try {
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Get product from database against given product ID
    val product = fetchProductFromDB(1001)

    // Add a string value as JsonValue
    val jsonValue = JsonValue(product.getProductName)

    // Create a unique key
    val key = "JSONProduct:" + product.getProductId

    // Create a new CacheItem for product and then insert
    val cacheItem = new CacheItem(jsonValue)

    // Add the string value in cache against the specified key
    cache.insert(key, cacheItem)

    // Retrieve the inserted value of the string against the key
    val retrievedValue = cache.get(key, classOf[JsonValue])
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

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.

  • .NET/.NET Core
  • Java
  • Scala
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";

    // Create a new CacheItem for product and then insert
    var cacheItemInt = new CacheItem(jsonInt);
    var cacheItemFloat = new CacheItem(jsonFloat);

    // Add these values in cache against the key specified
    cache.Insert(keyInt, cacheItemInt);
    cache.Insert(keyFloat, cacheItemFloat);

    // Retrieve the values added against the specified keys
    var retrievedValue = cache.Get<JsonValue>(keyInt);
}
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
}
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 and float value as JSON
    JsonValue jsonInt = new JsonValue(product.getProductID());
    JsonValue jsonFloat = new JsonValue(product.getUnitPrice());

    // Specify unique keys
    String keyInt = "Product:" + product.getProductID();
    String keyFloat = "Product:" + product.getProductID() + product.getUnitPrice();

    // Create a new CacheItem for product and then insert
    CacheItem cacheItemInt = new CacheItem(jsonInt);
    CacheItem cacheItemFloat = new CacheItem(jsonFloat);

    // Add these values in cache against the key specified
    cache.insert(keyInt,cacheItemInt);
    cache.insert(keyFloat,cacheItemFloat);

    // Retrieve the values added against the specified keys
    var retrievedValue = cache.get(keyInt,JsonValue.class);
}
catch(OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch(Exception ex)
{
  // Any generic exception like NullPointerException or IllegalArgumentException
}
try {
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Get product from database against given product ID
    val product = fetchProductFromDB(1001)

    // Add an integer and float value as JSON
    val jsonInt = new JsonValue(product.getProductId)
    val jsonFloat = new JsonValue(product.getPrice)

    // Specify unique keys
    val keyInt = "Product:" + product.getProductId
    val keyFloat = "Product:" + product.getProductId + product.getPrice

    // Create a new CacheItem for product and then insert
    val cacheItemInt = new CacheItem(jsonInt)
    val cacheItemFloat = new CacheItem(jsonFloat)

    // Add these values in cache against the key specified
    cache.insert(keyInt, cacheItemInt)
    cache.insert(keyFloat, cacheItemFloat)

    // Retrieve the values added against the specified keys
    val retrievedValue = cache.get(keyInt, classOf[JsonValue])
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

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.

  • .NET/.NET Core
  • Java
  • Scala
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";

    // Create a new CacheItem for product and then insert
    var cacheItem = new CacheItem(jsonValue);

    // Add the value of JSON DateTime in the cache
    cache.Insert(key, cacheItem);
}
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
}
try
{
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Add DateTime value as JSON
    LocalDateTime dateTime = LocalDateTime.now();
    JsonValue jsonValue = new JsonValue(dateTime);

    // Create a unique key
    String key = "JsonDataTime";

    // Create a new CacheItem for product and then insert
    CacheItem cacheItem = new CacheItem(jsonValue);

    // Add the value of JSON DateTime in the cache
    cache.insert(key, cacheItem);
}
catch(OperationFailedException ex){
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch(Exception ex)
{
    // Any generic exception like NullPointerException or IllegalArgumentException
}
try {
    // Pre-Condition: Cache is already connected

    // Cache is JSON serialized

    // Add DateTime value as JSON
    val dateTime = LocalDateTime.now
    val jsonValue = new JsonValue(dateTime)

    // Create a unique key
    val key = "JsonDataTime"

    // Create a new CacheItem for product and then insert
    val cacheItem = new CacheItem(jsonValue)

    // Add the value of JSON DateTime in the cache
    cache.insert(key, cacheItem)
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

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.

  • .NET/.NET Core
  • Java
  • Scala
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";

    // Create a new CacheItem for product and then insert
    var cacheItem = new CacheItem(jsonValue);

    // Add the value of JSON DateTime in the cache
    cache.Insert(key, cacheItem);
}
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
}
try
{

    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Specify a custom DateTime format
    String customDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSZ";

    // Add DateTime value as JSON
    // along with the custom datetime format
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(customDateTimeFormat);
    JsonValue jsonValue = new JsonValue(simpleDateFormat);

    // Create a unique key
    String key = "JsonDataTime";

    // Create a new CacheItem for product and then insert
    CacheItem cacheItem = new CacheItem(jsonValue);

    // Add the value of JSON DateTime in the cache
    cache.insert(key, cacheItem);
}
catch(OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch(Exception ex)
{
    // Any generic exception like NullPointerException or IllegalArgumentException
}
try {
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Specify a custom DateTime format
    val customDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSZ"

    // Add DateTime value as JSON
    // along with the custom datetime format
    val simpleDateFormat = new SimpleDateFormat(customDateTimeFormat)
    val jsonValue = new JsonValue(simpleDateFormat)

    // Create a unique key
    val key = "JsonDataTime"

    // Create a new CacheItem for product and then insert
    val cacheItem = new CacheItem(jsonValue)

    // Add the value of JSON DateTime in the cache
    cache.insert(key, cacheItem)
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

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.

  • .NET/.NET Core
  • Java
  • Scala
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}";

    // Create a new CacheItem for product and then insert
    var cacheItem = new CacheItem(jsonValue);

    // Add the boolean value in the cache against the key
    cache.Insert(key, cacheItem);

    // 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
}
try
{
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Create a new boolean value as JsonValue
    JsonValue jsonValue = new JsonValue(product.getIsContinued());

    // Create a unique key
    String key = "Product:1001";

    // Add the boolean value in the cache against the key
    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 NullPointerException or IllegalArgumentException
}
try {
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    val product = fetchProductFromDB(1001)

    // Create a new boolean value as JsonValue
    val jsonValue = new JsonValue(product.getIsContinued)

    // Create a unique key
    val key = "Product:1001"

    // Add the boolean value in the cache against the key
    cache.insert(key, jsonValue)
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

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.

  • .NET/.NET Core
  • Java
  • Scala
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";

    // Create a new CacheItem for product and then insert
    var cacheItem = new CacheItem(value);

    // Add the value in the cache against the key
    cache.Insert(key, cacheItem);

    // Retrieve the value against the specified key
    var retrievedValue = cache.Get<JsonValue>(key);

    // Convert the retrieved value to integer
    retrievedValue.ToInt32();
}
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
}
try
{
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Create a JsonValue as string
    String value = "10";
    JsonValue jsonValue = new JsonValue(value);

    // Create a unique key
    String key = "StringValue";

     // Create a new CacheItem for product and then insert
    CacheItem cacheItem = new CacheItem(value);

    // Add the value in the cache against the key
    cache.insert(key, cacheItem);

    // Retrieve the value against the specified key
    JsonValue retrievedValue = InitializeCache.cache.get(key,JsonValue.class);

    // Convert the retrieved value to integer
    retrievedValue.toInt32();
}
catch(OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch(Exception ex)
{
   // Any generic exception like NullPointerException or IllegalArgumentException
}
try {
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Create a JsonValue as string
    val value = "10"
    val jsonValue = new JsonValue(value)

    // Create a unique key
    val key = "StringValue"

    // Create a new CacheItem for product and then insert
    val cacheItem = new CacheItem(value)

    // Add the value in the cache against the key
    cache.insert(key, cacheItem)

    // Retrieve the value against the specified key
    val retrievedValue = cache.get(key, classOf[JsonValue])

    // Convert the retrieved value to integer
    retrievedValue.toInt32
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

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.

  • .NET/.NET Core
  • Java
  • Scala
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";

    // Create a new CacheItem for product and then insert
    var cacheItem = new CacheItem(jsonValue);

    // Add the value in the cache against the key
    cache.Insert(key, cacheItem);

    // 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
    // The value according to your logic will be retrieved
    retrievedValue.ToDouble();

}
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
}
try{
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Add an integer as JsonValue
    int value = 1000;
    JsonValue jsonValue = new JsonValue(value);

    // Create a unique key
    String key = "JsonValue";

    // Create a new CacheItem for product and then insert
    CacheItem cacheItem = new CacheItem(jsonValue);

    // Add the value in the cache against the key
    cache.insert(key, cacheItem);

    // Retrieve the value against the specified key
    JsonValue retrievedValue = InitializeCache.cache.get(key,JsonValue.class);

    // Convert the json value to string
    retrievedValue.toStringValue();

    // Convert the json value to double
    // The value according to your logic will be retrieved
    retrievedValue.toDouble();
}
catch(OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch(Exception ex)
{
    // Any generic exception like NullPointerException or IllegalArgumentException
}
try {
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Add an integer as JsonValue
    val value = 1000
    val jsonValue = new JsonValue(value)

    // Create a unique key
    val key = "JsonValue"

    // Create a new CacheItem for product and then insert
    val cacheItem = new CacheItem(jsonValue)

    // Add the value in the cache against the key
    cache.insert(key, cacheItem)

    // Retrieve the value against the specified key
    val retrievedValue = cache.get(key, classOf[JsonValue])

    // Convert the json value to string
    retrievedValue.toStringValue

    // Convert the json value to double
    // The value according to your logic will be retrieved
    retrievedValue.toDouble
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }
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 the boolean value as string. However, you cannot retrieve boolean as DateTime 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.

  • .NET/.NET Core
  • Java
  • Scala
try
{
    bool value = true;
    JsonValue json = value;
    json.ToDateTime();
}
catch(Exception ex)
{
    // Handle exception accordingly
}
try
{
    boolean value = true;
    JsonValue jsonValue = new JsonValue(value);
    jsonValue.toDate();
}
catch(Exception ex)
{
    // Handle exception accordingly
}
try {
    val value = true
    val jsonValue = new JsonValue(value)
    jsonValue.toDate
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

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 or DateTime results in an exception. Make sure that the value of boolean string is True or False 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.

  • .NET/.NET Core
  • Java
  • Scala
try
{
    string boolStr = "true";
    JsonValue json = (JsonValue)boolStr;
    json.ToInt32();
}
catch(Exception ex)
{
    // Handle Exception accordingly
}
try
{
    String boolStr = "true";
    JsonValue jsonValue = new JsonValue(boolStr);
    jsonValue.toInt32();
}
catch(Exception ex)
{
    // Handle Exception accordingly
}
try {
    val boolStr = "true"
    val json = boolStr.asInstanceOf[JsonValue]
    json.toInt32
  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

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 than DateTime, 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.

  • .NET/.NET Core
  • Java
  • Scala
try
{
    JsonValue jsonDate = DateTime.Now;
    jsonDate.ToInt32();
}
catch(Exception ex)
{
    // Handle exception accordingly
}
try
{
    JsonValue jsonValue = new JsonValue(LocalDateTime.now());
    jsonValue.toInt32();
}
catch(Exception ex)
{
    // Handle Exception accordingly
}
try {
    val jsonValue = new JsonValue(LocalDateTime.now)
    jsonValue.toInt32

  }
  catch {
    case exception: Exception => {
      // Handle any errors
    }
  }

An exception occurs saying Input string was not in a correct format on performing the specified function.

  • The data structures Float, Decimal and Double 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 as boolean.

Number Floating Number Boolean String DateTime
Signed (Decimal, Float, Double are always signed) Allowed
  • True (All numbers except 0)
  • False (0)
  • Number in string format Not allowed
    Unsigned Allowed
  • True (All numbers except 0)
  • False (0)
  • Number in string format Not allowed
    Floating Number Number Boolean String DateTime
    Signed Rounded to nearest value
  • True (All numbers except 0)
  • False (0)
  • Number in string format Not allowed
    Unsigned Rounded to nearest value
  • True (All numbers except 0)
  • False (0)
  • Number in string format Not allowed

    The following example shows the behavior of an integer, returned as boolean.

    • .NET/.NET Core
    • Java
    • Scala
    try
    {
        int integer = 30;
        JsonValue integerValue = integer;
        bool boolVal = integerValue.ToBoolean();
    }
    catch(Exception ex)
    {
        // Handle exception accordingly
    }
    
    try
    {
        int integer = 30;
        JsonValue integerValue = new JsonValue(integer);
        boolean boolVal = integerValue.toBoolean();
    }
    catch(Exception ex)
    {
        /// Handle exception accordingly
    }
    
    try {
        val integer = 30
        val integerValue = new JsonValue(integer)
        val boolVal = integerValue.toBoolean
      }
      catch {
        case exception: Exception => {
          // Handle any errors
        }
      }
    

    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.

    • .NET/.NET Core
    • Java
    • Scala
    try
    {
        string value = "Product Details";
        JsonValue stringValue = (JsonValue)value;
        stringValue.ToInt64();
    }
    catch (Exception ex)
    {
        // Handle exception accordingly
    }
    
    try
    {
        String value = "Product Details";
        JsonValue stringValue = new JsonValue(value);
        stringValue.toInt64();
    }
    catch(Exception ex)
    {
        // Handle exception accordingly
    }
    
    try {
        val value: String = "Product Details"
        val stringValue = new JsonValue(value)
        stringValue.toInt64
      }
      catch {
        case exception: Exception => {
          // Handle any errors
        }
      }
    

    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 on GitHub.

    See Also

    Overview
    Using JsonObject in Cache
    Using JsonArray in Cache
    Cache Serialization Format

    Back to top Copyright © 2017 Alachisoft