String values that represent JSON primitive values can also be read. For example, JSON("true") returns a SpinJsonNode that represents the boolean value true.
Reading JSON from a Reader:
Spin also supports reading JSON from an instance of java.io.Reader:
importstatic org.camunda.spin.Spin.*;
importstatic org.camunda.spin.DataFormats.*;
SpinJsonNode json = S(reader, json());
The JSON(…) method also supports readers. The following example shows how to read JSON from a file (error handling ommitted):
JSON can be read from script languages in the same way as from Java. Since script languages use dynamic typing, you do not need to hint the data format but you can use autodetection. The following example demonstrates how to read JSON in Javascript:
var customer = S('{"customer": "Kermit"}');
Reading JSON Properties
To fetch properties from the JSON tree you can use .prop("name"). This will return the property as SpinJsonNode and you can use this to get the value of the property as the following examples will demonstrate:
The method SpinJsonNode#value() can be used to get the Java equivalent of a String/Boolean/Number or null JSON property. It throws an exception for Object and Array properties. There are also:
stringValue() - gets a Java String representation of the value or throws an exception if the value is not a String
numberValue() - gets a Java Number representation of the value or throws an exception if the value is not a Number
boolValue() - gets a Java Boolean representation of the value or throws an exception if the value is not a Boolean
Value type checks of the property
isObject() returns boolean
hasProp() returns boolean
isBoolean() returns boolean
isNumber() returns boolean
isString() returns boolean
isNull() returns boolean
isValue() returns boolean
isArray() returns boolean Script example (JavaScript):
var json = S('{"over18":false}');
json.prop('over18').isBoolean()//returns true
Fetch Array of Data
You can also fetch a list of items if your property is an array of data.
var json = S('{"customer": ["Kermit", "Waldo"]}');
var customerProperty = json.prop("customer");
var customers = customerProperty.elements();
var customer = customers.get(0)
var customerName = customer.value();
Fetch Field Names
Spin allows us to use the .fieldNames() method to fetch the names of all child nodes and properties in a node. The following example shows you how to use .fieldNames() in Java and Javascript.