Java Reference
In-Depth Information
Serializing Objects
Nashorn supports serializing and desterilizing of object using a built-in object called
JSON
. JSON is also an acronym that stands for
J
ava
S
cript
O
bject
N
otation that specifies
how a JavaScript object is converted to a string and vice versa. JSON is a Data Interchange
object contains two methods:
JSON.stringify(value, replacer, indentation)
•
JSON.parse(text, reviver)
The
JSON.stringify()
method converts a Nashorn value into a string. The
JSON.
parse()
method converts a string in JSON format into a Nashorn value.
The
value
parameter in the
stringify()
method can be an object or a primitive
value. Not all types of values can be stringified. For example,
undefined
cannot be
stringified.
NaN
and
Infinity
are stringified as
null
.
The
replacer
argument is a
function
or an array. If
replacer
is a function, it is takes
two parameter. The first parameter is the name of the property being stringified and the
second one is the value of the property. The returned value of the function is used as the
final value to be stringified. If the function returns
undefined
or no value, the property is not
stringified. The first time
replacer
is called with the empty string as the property name
and the object being stringified as the value. Subsequent calls pass the property
name and the property value of the property being stringified. If
replacer
is an array, it
contains the names of the properties to be stringified. Any properties not appearing in the
array will not be stringified.
The
indentation
is a number or a string used for indentation in the output. If it is a
number, it is the number of spaces to be used for indentation. Its value is capped at 10.
If it is a string such as
"\t"
, it is used for indentation at each level. The
replacer
and
indentation
parameters are optional in the
stringify()
method.
The
reviver
is a function that is called when the JSON text is being parsed into an
object. It takes two parameters. The first parameter is the name of the property being
parsed and the second one is the value of the property. If the function returns
null
or
undefined
, the corresponding property is deleted.
Listing 4-19 demonstrates the use of the
JSON
object. It stringifies an object. During
stringification, it multiplies the values of the properties by 2. During parsing, it applies the
reverse logic to restore the object.
•
Listing 4-19.
Using the JSON Object to Stringify and Parse Objects
// json.js
var point = {x: 10, y: 20};
function replacer (key, value) {
if (key === "x" || key === "y") {
// Multiply the value by 2
return value * 2;
}
Search WWH ::
Custom Search