Class: cJsonObject
Properties | Events | Methods | Index of Classes
Represents a single JSON node within a structure of JSON nodes
Hierarchy
cObject > cJsonObject
Show full hierarchy and direct subclasses
- cObject
- cJsonObject
Library: Common Class Library
Description
The cJsonObject represents a single JSON node within a structure of JSON nodes.
A JSON node can represent an object, array, simple type (string, number and Boolean) or null value.
The class contains the entire API for generating, parsing and enumerating JSON. The JsonToDataType and DataTypeToJson methods can be used to parse a JSON document into struct and / or arrays.
This class can be used to parse and generate JSON. It is also capable of converting structs and arrays into JSON and JSON into structs and arrays. A cJsonObject instance represents a single node in a structure of JSON nodes. It can represent an object, array, simple type (string, number, Boolean) or a null value. Once initialized (by either parsing, using DataTypeToJson or calling InitJsonType) its API's can be used to enumerate or generate the JSON.
Parsing JSON
To parse JSON the ParseString or ParseUtf8 functions can be used. Both functions return a Boolean indicating if the parse was successful. If not ReportParseError or psParseError can be used to get information about the parse error.
Sample
The example below shows how to parse a string with JSON. If successful it reads the age member from the details object. If not successful it uses ReportParseError that will generate an error.
Handle hoJson hoDetails
Boolean bSuccess
Integer iAge
Get Create (RefClass(cJsonObject)) to hoJson
Get ParseString of hoJson '{"name" : "John", "details" : {"age" : 31, "male" : true}}' to bSuccess
If (bSuccess) Begin
Get Member of hoJson "details" to hoDetails
Get MemberValue of hoDetails "age" to iAge
Showln ("Age of John: " + String(iAge))
Send Destroy of hoDetails
End
Else Begin
Send ReportParseError of hoJson
End
Send Destroy of hoJson
Generating JSON
Generating JSON can be done by calling Stringify on an initialized JSON object. The peWhitespace property on this object determines how the JSON will be spaced. To inialize JSON manually, the InitializeJsonType procedure can be used.
Sample
The example below initializes a JSON object, sets the name member, creates and initializes the member object, sets two members and then sets the member object as a member of the wrapping JSON object. Running this code results in the following JSON. { "name": "John", "details": { "age": 31, "male": true } }
Handle hoJson hoDetail
String sJson
Get Create (RefClass(cJsonObject)) to hoJson
Send InitializeJsonType of hoJson jsonTypeObject
Send SetMemberValue of hoJson "name" jsonTypeString "John"
// Initialize detail object
Get Create (RefClass(cJsonObject)) to hoDetail
Send InitializeJsonType of hoDetail jsonTypeObject
Send SetMemberValue of hoDetail "age" jsonTypeInteger 31
Send SetMemberValue of hoDetail "male" jsonTypeBoolean True
Send SetMember of hoJson "details" hoDetail
Send Destroy of hoDetail
// Generate JSON string
Set peWhiteSpace of hoJson to jpWhitespace_Spaced
Get Stringify of hoJson to sJson
Showln sJson
Send Destroy of hoJson
Traversing Structure
A JSON document should be seen as a tree of objects, arrays and simple type nodes as leaves. A cJsonObject instance represents a single node in that tree and there are several API's available to traverse the tree. The JsonType and MemberJsonType functions can be used to determine the type of a specific node.
The MemberCount function returns the number of members on an object or an array and using Member or MemberByIndex members can be enumerated. When Member or MemberByIndex is used to obtain a handle to a member node, this handle needs to be destroyed manually. Note that destroying a member handle does not actually change the JSON document.
Sample
The example below enumerates a JSON object showing information about its members. It outputs the following: Member 'name' of type 6 Member 'details' of type 4
Handle hoJson hoMember
Integer iMem iType
String sName
Boolean bSuccess
Get Create (RefClass(cJsonObject)) to hoJson
Get ParseString of hoJson '{"name" : "John", "details" : {"age" : 31, "male" : true}}' to bSuccess
If (bSuccess) Begin
For iMem from 0 to (MemberCount(hoJson) - 1)
Get MemberNameByIndex of hoJson iMem to sName
Get MemberByIndex of hoJson iMem to hoMember
Get JsonType of hoMember to iType
Showln (SFormat("Member '%1' of type %2", sName, iType))
Send Destroy of hoMember
Loop
End
Begin
Send ReportParseError of hoJson
End
Send Destroy of hoJson
Sample
The following example shows how enumerate array members. Note that in this example we do not get a handle to the member node first but access it directly using MemberValue which can be used for both arrays and objects.
The output of this example will be: Member 0 has value 8 Member 1 has value 7,5 Member 2 has value 8 Member 3 has value 5,5
Handle hoJson
Boolean bSuccess
Integer iMem
Number nVal
Get Create (RefClass(cJsonObject)) to hoJson
Get ParseString of hoJson '[ 8, 7.5, 8, 5.5 ]' to bSuccess
If (bSuccess) Begin
For iMem from 0 to (MemberCount(hoJson) - 1)
Get MemberValue of hoJson iMem to nVal
Showln (SFormat("Member %1 has value %2", iMem, nVal))
Loop
End
Else Begin
Send ReportParseError
End
Send Destroy of hoJson
Converting Structs
A good method to easily serialize and deserialize data is available with the JsonToDataType and DataTypeToJson methods. They can be used to convert data stored in structs to JSON and the other way around.
Sample
The example below defines a set of structs and arrays. It then parses some JSON uses JsonToDataType to convert the JSON into usable struct data. The output of the this example will be 'Student "John" has 4 ratings'.
Struct tStudentDetail
Integer age
Boolean male
End_Struct
Struct tStudent
String name
tStudentDetail details
Number[] ratings
End_Struct
Procedure ReadIntoStruct
Handle hoJson
tStudent student
Boolean bSuccess
Get Create (RefClass(cJsonObject)) to hoJson
Get ParseString of hoJson '{"name" : "John", "details" : {"age" : 31, "female" : false, "male" : true}, "ratings" : [ 8, 7.5, 8, 5.5 ]}' to bSuccess
If (bSuccess) Begin
// Convert JSON structure into struct
Get JsonToDataType of hoJson to student
Showln (SFormat('Student "%1" has %2 ratings', student.name, SizeOfArray(student.ratings)))
End
Else Begin
Send ReportParseError of hoJson
End
Send Destroy of hoJson
End_Procedure
Sample
This example demonstrates the other way arround where a struct with data is used to generate JSON. { "name": "John", "details": { "age": 31, "male": true }, "ratings": [ 8, 7.5, 8, 5.5 ] }
Procedure StructToJson
Handle hoJson
tStudent student
String sJson
Move "John" to student.name
Move 31 to student.details.age
Move True to student.details.male
Move 8 to student.ratings[0]
Move 7.5 to student.ratings[1]
Move 8 to student.ratings[2]
Move 5.5 to student.ratings[3]
Get Create (RefClass(cJsonObject)) to hoJson
// Convert struct to JSON structure
Send DataTypeToJson of hoJson student
Set peWhiteSpace of hoJson to jpWhitespace_Spaced
Get Stringify of hoJson to sJson
Showln sJson
Send Destroy of hoJson
End_Procedure