The procedure to call a Python decode method for the different cases described above is basically the same. It involves the following steps:
Create a decode message buffer object on the data to be decoded, from which the value will be decoded.
Invoke the decode method.
The first step is the creation of a decode message buffer
object. An Asn1JsonDecodeBuffer
can be created
on any io.TextIOBase object, or you can use the convenience class
method from_text
to create one from a string of
JSON text. For example:
# Create buffer on a JSON text file decbuf = Asn1JsonDecodeBuffer(open(filename, 'r')) # Create a buffer on JSON text decbuf = Asn1JsonDecodeBuffer.from_text(json_text)
The decode method itself is then invoked. In the simple case of a primitive type with no generated class, this involves invoking one of the methods defined in the decode buffer class to decode a primitive value. For example, to decode an integer, do:
value = decbuf.read_int()
This would decode the content at the current decode buffer cursor position, which is expected to be a JSON number representing an integer.
The procedure for invoking a static method is similar. The
general form is <classname>.json_decode(decbuf).
For example, a class named EmployeeNumber
would be
generated for the following definition:
EmployeeNumber ::= INTEGER(0..100)
To decode an employee number, do the following:
value = EmployeeNumber.json_decode(decbuf)
This would decode the JSON number and check to ensure the constraint
is satisfied. If successful, the decoded integer value will assigned to
value
.
Finally, to invoke an instance method in a class generated for a constructed type, first create an instance of the class and then invoke the generated decode method:
jSmithName = Name() jSmithName.json_decode(decbuf)
If successful, the attributes of the jSmithName instance will be populated with the decoded values.
A complete example showing how to invoke a decode method is as follows:
try: # Step 1: create a decode buffer. This example uses a file for input. f = open(in_filename, 'r') decbuf = Asn1JsonDecodeBuffer(f) # Step 2: create an object of the generated type and invoke the decode # method. personnelRecord = PersonnelRecord() personnelRecord.json_decode(decbuf) f.close() personnelRecord.print_value("personnelRecord", 0) except Exception: print(traceback.format_exc()) sys.exit(-1)