RingDotNetfor Ring

Writing JSON as a stream

Utf8JsonWriter writes a JSON text piece by piece into a stream, with exact control of the form and without building the whole document in memory first. This lesson writes an object with nested parts, shows the escaping and the checks the writer does, and uses JsonSerializer with options.

What you will learn#

The tutorial JSON and XML read and wrote JSON as a tree and the tutorial JSON as a tree built it from nodes. A tree is easy to change but it keeps the whole document in memory. A writer is the other style: you say what comes next, and it goes straight to a stream (a file, a network connection, a MemoryStream).

The program#

samples/UsingDotNet/tutorials/ch02_json_writer.ring
# writing JSON as a stream - Utf8JsonWriter, indentation, nesting, escaping, and JsonSerializer options
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Text"
	"System.Text.Json"
}

func main

	# 1. Utf8JsonWriter writes a JSON text piece by piece into a stream, without building a tree in memory first.
	#    It is the right tool for big documents and for output that must be exactly formatted.
	oStream = new MemoryStream
	oOptions = new JsonWriterOptions()
	oOptions.Indented = True
	oWriter = (new Utf8JsonWriter).@New([ :utf8Json = oStream, :options = oOptions ])
	oWriter.WriteStartObject(NULL)
	oWriter.WriteString("name","Ann")
	oWriter.WriteNumber("age",31)
	oWriter.WriteBoolean("active",True)
	oWriter.WriteNull("manager")
	oWriter.WriteStartArray("skills")
	oWriter.WriteStringValue("ring")
	oWriter.WriteStringValue(".NET")
	oWriter.WriteEndArray()
	oWriter.WriteStartObject("address")
	oWriter.WriteString("city","Cairo")
	oWriter.WriteEndObject()
	oWriter.WriteEndObject()
	oWriter.Flush()                      # the writer keeps a buffer: Flush sends it to the stream
	cJson = new UTF8Encoding().GetString(oStream.ToArray())
	? "1. the document:"
	? substr(cJson,char(13),"")
	oWriter.Dispose()

	# 2. The same document in one line (not indented): the writer adds no spaces
	oStream2 = new MemoryStream
	oWriter2 = new Utf8JsonWriter(oStream2)
	oWriter2.WriteStartArray(NULL)
	for n = 1 to 3
		oWriter2.WriteNumberValue(n * n)
	next
	oWriter2.WriteEndArray()
	oWriter2.Flush()
	? nl + "2. one line: " + new UTF8Encoding().GetString(oStream2.ToArray())
	oWriter2.Dispose()

	# 3. Escaping is done for you. The writer also refuses a document that is not valid: a value without a property name inside an
	#    object, or an end without a start, raises an error (that is a test of your own program).
	oStream3 = new MemoryStream
	oWriter3 = new Utf8JsonWriter(oStream3)
	oWriter3.WriteStartObject(NULL)
	oWriter3.WriteString("text",'a "quoted" line' + nl + 'and a <tag> & more')
	oWriter3.WriteEndObject()
	oWriter3.Flush()
	? nl + "3. escaped: " + new UTF8Encoding().GetString(oStream3.ToArray())
	lError = False
	try
		oWriter3.WriteEndObject()           # there is no object to end
	catch
		lError = True
	done
	? "   an end without a start is an error: " + lError

	# 4. JsonSerializer turns .NET objects into JSON; JsonSerializerOptions choose the form. A list of numbers and a dictionary:
	oSerializer = new JsonSerializer()
	oNumbers = new List([ :typeArguments = ["System.Int32"] ])
	for n in [3,1,2]
		oNumbers.Add(n)
	next
	? nl + "4. a list: " + oSerializer.Serialize(oNumbers)
	oScores = new Dictionary([ :typeArguments = ["System.String","System.Double"] ])
	oScores.Add("ann",9.5)
	oScores.Add("bob",7)
	? "   a dictionary: " + oSerializer.Serialize(oScores)
	oIndent = new JsonSerializerOptions()
	oIndent.WriteIndented = True
	? "   indented: " + substr(substr(oSerializer.Serialize([ :value = oScores, :options = oIndent ]),char(13),""),nl," ")
Output
1. the document:
{
  "name": "Ann",
  "age": 31,
  "active": true,
  "manager": null,
  "skills": [
    "ring",
    ".NET"
  ],
  "address": {
    "city": "Cairo"
  }
}

2. one line: [1,4,9]

3. escaped: {"text":"a \u0022quoted\u0022 line\nand a \u003Ctag\u003E \u0026 more"}
   an end without a start is an error: 1

4. a list: [3,1,2]
   a dictionary: {"ann":9.5,"bob":7}
   indented: {   "ann": 9.5,   "bob": 7 }
Note

This program uses a few generic functions (dnNew, dnNewGeneric) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Writing the document#

The writer is made on a stream (dnNew("Utf8JsonWriter",[ :utf8Json = oStream, :options = oOptions ])). Then you call, in order, what the document contains:

CallWrites
WriteStartObject(NULL) / WriteEndObject(){ and } (with a name, WriteStartObject("address"), it is a property of the object around it)
WriteStartArray("skills") / WriteEndArray()[ and ]
WriteString("name","Ann")a property with a text value
WriteNumber("age",31), WriteBoolean("active",True), WriteNull("manager")properties with other values
WriteStringValue("ring"), WriteNumberValue(4)a value inside an array (it has no name)

The names and the commas, colons and quotes are added by the writer: you never write a , yourself. JsonWriterOptions is a struct; its property Indented = True makes the readable form with two spaces for each level. Without it (step 2) the text is compact, [1,4,9], which is what a program sends over a network.

Note

The writer has several forms of each method, and Ring takes the plain WriteString("name","Ann") (two values) or WriteStartObject(NULL) (no name). If you get "less number of parameters", look at the method in the class reference: a method with two or more values is called with them in order.

Flush#

The writer keeps its output in a buffer and sends it to the stream in blocks. Flush() sends what is waiting: without it the stream can still be empty (or incomplete) when you read it. Dispose() flushes and releases the writer, so close it when you are done (the tutorial Releasing resources).

Escaping and checks#

The text a "quoted" line followed by a new line and <tag> & more is written as a "quoted" line\nand a <tag> & more: quotes, new lines and the characters <, >, & are escaped, so the output is valid JSON and also safe to put into a web page (the tutorial Escaping). The writer also checks the structure: ending an object that was not started raises an error (here caught with try). Such an error is a bug in your program that you can find at once, instead of a broken file that a receiver finds later.

JsonSerializer#

JsonSerializer.Serialize(object) turns a .NET object — a list, a dictionary, an object of your own library — into JSON in one call. JsonSerializerOptions change the form: WriteIndented, PropertyNamingPolicy (for example camelCase), DefaultIgnoreCondition (skip null values) and more. The method has several forms, so with options it takes names: Serialize([ :value = oScores, :options = oIndent ]). Use the serializer when you have objects, and the writer when you want to control every token or write very large output.

What you learned#

Exercises#

  1. Write an array of 1000 objects with id and square into a file (the tutorial Files and folders), and read it back with JsonDocument (the tutorial JSON and XML).
  2. Write the nested folder structure of a directory as JSON with a recursive function.
  3. Make JsonSerializerOptions with PropertyNamingPolicy = JsonNamingPolicy.CamelCase and look at the names.
  4. Write a number with many decimals with WriteNumber and look at how it is written.

Next#

JSON as a tree

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.