Tc3JsonXmlSampleJsonSaxReader
Sample of the parsing of JSON documents via SAX Reader
This sample illustrates how a JSON message can be run through programmatically. The function block FB_JsonSaxReader is used as the basis.
Declaration range
PROGRAM MAIN
VAR
fbJson : FB_JsonSaxReader;
pJsonParse : JsonSaxHandler;
sJsonDoc : STRING(255) := '{"Values":{"Timestamp":"2017-04-04T12:42:42","Sensor1":42.42,"Sensor2":42}}';
END_VAR
Implementation range
Through the calling of the Parse() method, the transfer of the JSON message as a STRING and the interface pointer to a function block instance that implements the interface ItcJsonSaxHandler, the SAX Reader is activated and the corresponding callback methods are run through.
fbJson.Parse(sJson := sJsonDoc, ipHdl := pJsonParse);
Callback methods
The callback methods are called on the instance of the function block that implements the interface ItcJsonSaxHandler. Each callback method represents a "found" element in the JSON message. For example, the callback method OnStartObject() is called as soon as an opening curly bracket has been detected. According to the example JSON message mentioned above, therefore, the following callback methods are run through in this order:
- OnStartObject(), due to the first opening curly bracket
- OnKey(), due to the property "Values"
- OnStartObject(), due to the second opening curly bracket
- OnKey(), due to the property "Timestamp"
- OnString(), due to the value of the property "Timestamp"
- OnKey(), due to the property "Sensor1"
- OnLreal(), due to the value of the property "Sensor1"
- OnKey(), due to the property "Sensor2"
- OnUdint(), due to the value of the property "Sensor2"
- OnEndObject(), due to the first closing curly bracket
- OnEndObject(), due to the second closing curly bracket
Within the callback methods the current state is defined and saved via an instance of the enum E_JsonStates. This can also be used to determine whether the JSON message is valid. For example, if the callback method OnLreal() is called and the state is not the expected State 70 (JSON_STATE_ONLREAL), the return value S_FALSE can be returned to the method. The SAX Reader then automatically cancels the further processing.