You are here: Web Services > Working with JSON Data > Using XPRIM_JsonWriter to Construct JSON Strings

Using XPRIM_JsonWriter to Construct JSON Strings

Although you can serialize your XPRIM_JsonObject or XPRIM_JsonArray into a JSON string, if all you want to do is construct a JSON string, or construct a JSON body for XPRIM_HttpRequest, you should use XPRIM_JsonWriter, as it is designed to efficiently construct JSON strings. XPRIM_JsonWriter has a much better performance and lower memory footprint, especially for big JSON data.

As an example, let's use XPRIM_JsonWriter to construct the following JSON string:

{

    "name":
    {

        "given": "John",

        "surname": "Smith"

    },

    "age": 45,

    "contactNo":

    [

        { area: "02", no: "9378 2867", type: "landline" },

        { no: "0468 732 371", type: "mobile" }

    ]

}

Start by creating an XPRIM_JsonWriter object.

Define_Com Class(#XPRIM_JsonWriter) Name(#Writer)

Specify the output mode of the writer. Three output modes are supported:

Use the following methods to specify the output mode:

In this example, we are going to generate a string, so set the output mode to String.

#Writer.SetOutputToString

Use BeginObject (or BeginArray if you are creating an array) to start the root object (or array).

#Writer.BeginObject

We now want to write the "name" member, whose value is an object.

Use BeginObject with Name parameter to create an object member.

#Writer.BeginObject Name('name')

So far, our JSON string looks like this:

{

    "name":
    {

Let's now write the "given" and "surname" member.

#Writer.WriteString Name('given') Value('John')

#Writer.WriteString Name('surname') Value('Smith')

Close the name member object:

#Writer.EndObject

So far, our JSON string looks like this:

{

    "name":
    {

        "given": "John",

        "surname": "Smith"

    }

Write the "age" member:

#Writer.WriteNumber Name('age') Value(45)

Write the "contactNo" member, which is an array. We'll use BeginArray.

#Writer.BeginArray Name('contactNo')

Let's now write the first contactNo item, which is an object, so we'll use BeginObject.  When writing array elements, we don't need to specify any index as they will always be written out sequentially.

#Writer.BeginObject

#Writer.WriteString Name('area') Value('02')

#Writer.WriteString Name('no') Value('9378 2867')

#Writer.WriteString Name('type') Value('landline')

#Writer.EndObject

Write the second contactNo item.

#Writer.BeginObject

#Writer.WriteString Name('no') Value('0468 732 371')

#Writer.WriteString Name('type') Value('mobile')

#Writer.EndObject

Close the contactNo array.

#Writer.EndArray

Close the root object.

#Writer.EndObject

You can now access the construct JSON string using the AsString method:

#MyJsonString := #Writer.AsString

Next: Using XPRIM_RandomAccessJsonReader to Read JSON Values