Procedure for Calling JSON Encode Methods

Once an object's member variables have been populated, the object's encode method can be invoked to encode the value. The general procedure to do this involves the following three steps:

  1. Create an encode output stream into which the value will be encoded.

  2. Invoke the encode method.

  3. Close the output stream.

The first step is the creation of an encode output stream, an Asn1JsonOutputStream. There is a single constructor which accepts a System.IO.TextWriter. As usual, output can be directed to a string, a stream, a file-backed stream, a memory (array)-backed stream, etc. by making appropriate use of the .NET framework classes.

The second step is the invocation of the encode method. The calling arguments were described earlier.

Finally, close the output stream.

A complete example showing how to invoke an encode method is as follows:

   // Note: personnelRecord object was previously populated with data

   Asn1JsonOutputStream encodeStream = null;

   try {
       // Step 1: Create an encode output stream, with UTF-8 character encoding
       // Note the use of the UTF8Encoding constructor to avoid writing a UTF-8 BOM to the file.
       encodeStream = new Asn1JsonOutputStream (
          new System.IO.StreamWriter( new System.io.FileStream(filename, System.IO.FileMode.Create), 
             new System.Text.UTF8Encoding(false,true)) );

      // Step 2: Invoke the encode method.

       personnelRecord.Encode (encodeStream);

       if (trace) {
           System.Console.Out.WriteLine("Encoding was successful");
       }
   }
   catch (Exception e) {
      System.Console.Out.WriteLine(e.Message);
      Asn1Util.WriteStackTrace(e, Console.Error);
      Environment.Exit(1);
   }
   finally {
      try {
         if (encodeStream != null) encodeStream.Close ();
      }
      catch (Exception e) {}
   }