This is a set of helper classes for working with web requests and web content in DataFlex.
- The
cJSONParser
class helps you parse JSON strings using theParse
procedure. - The
cJSONDictionary
class helps you access, mutate and serialize JSON objects. It depends on cHashTable and cRegex.
Procedure ParsingExample
Handle hParser hDictionary
String sJSON sValue
Move '{"stringValue": "this is a string"}' to sJSON
Get Create U_cJSONParser to hParser
Get Create U_cJSONDictionary to hDictionary
Send Parse of hParser sJSON hDictionary
If (Found) Begin
Get Value of hDictionary "stringValue" to sValue // "this is a string"
End
Send Destroy of hParser
Send Destroy of hDictionary
End_Procedure
Procedure ParsingExample
Handle hParser hDictionary
String sJSON sValue
Variant[] vaArray
Move '["first", "second", "third"]' to sJSON
Get Create U_cJSONParser to hParser
Get Create U_cJSONDictionary to hDictionary
Send Parse of hParser sJSON hDictionary
If (Found) Begin
Get Value of hDictionary "_array" to vaArray // "_array" is a pseudo element for top-level JSON arrays
Move vaArray[1] to sValue // "second"
End
Send Destroy of hParser
Send Destroy of hDictionary
End_Procedure
Let's recreate this JSON string using DataFlex:
{
"type": "Horse",
"properties": {
"legs": 4,
"hasStripes": false
},
"relatedAnimals": [
"Zebra",
"Mule"
]
}
Procedure SerializingExample
Handle hAnimal hProperties
Variant[] vaRelatedAnimals
String sJSON
Move "Zebra" to vaRelatedAnimals[0]
Move "Mule" to vaRelatedAnimals[1]
Get Create U_cJSONDictionary to hAnimal
Get Create U_cJSONDictionary to hProperties
Set TypedValue of hAnimal "type" _jsond_string to "Horse"
Set TypedValue of hAnimal "properties" _jsond_object to hProperties
Set TypedValue of hAnimal "relatedAnimals" _jsond_array to vaRelatedAnimals
Set TypedValue of hProperties "legs" _jsond_number to 4
Set TypedValue of hProperties "hasStripes" _jsond_bool to false
Get Serialize of hAnimal to sJSON // { "type": "Horse", ... }
Send Destroy of hAnimal
Send Destroy of hProperties
End_Procedure