# JSON Class

The JSON class can be used to parse and write JSON documents.

## Syntax

```text
JSON
```

## Remarks

The JSON class offers a fast and simple way to parse and write information in JSON documents.

### Parsing JSON

The JSON class parses JSON documents and verifies that they are well-formed. The results are provided through a set of events.

In addition, the document structure may be queried through an [XPath](#xpath-property-json-class) mechanism that supports a subset of the XPath and JSONPath specification.

The parser is optimized for read applications, with a very fast engine that builds internal DOM structures with close to zero heap allocations. Additionally, [BuildDOM](#builddom-property-json-class) can be set to False, which reduces the overhead of creating the DOM and offers a fast forward-only parsing implementation that fires events to provide the parsed data.

When parsing a document, events will fire to provide information about the parsed data. After [Parse](#parse-method-json-class) returns the document, it may be navigated by setting [XPath](#xpath-property-json-class) if [BuildDOM](#builddom-property-json-class) is True (default). If [BuildDOM](#builddom-property-json-class) is False, parsed data are accessible only through the events.

The following events will fire during parsing:

- [StartElement](#startelement-event-json-class)
- [Characters](#characters-event-json-class)
- [EndElement](#endelement-event-json-class)
- [IgnorableWhitespace](#ignorablewhitespace-event-json-class)

If [BuildDOM](#builddom-property-json-class) is True (default), [XPath](#xpath-property-json-class) may be set after this method returns. [XPath](#xpath-property-json-class) may be set to navigate to specific elements within the JSON document. This will be the path to a specified value within the document. Because arrays in JSON only contain values, and no associated object name, an empty name will be used for these values. To reach an array element at position 1, the path must be set to "[1]". In addition, a root element named "json" will be added to each JSON document in the parser.

[BuildDOM](#builddom-property-json-class) must be set to True before parsing the document for the [XPath](#xpath-property-json-class) functionality to be available.

The [XPath](#xpath-property-json-class) property accepts both XPath and JSONPath formats. Please review the following notes on both formats.

### XPath

The path is a series of one or more element accessors separated by '/'. The path can be absolute (starting with '/') or relative to the current [XPath](#xpath-property-json-class) location.

 The following are possible values for an element accessor:

|  |  |
| --- | --- |
| 'name' | A particular element name. |
| [i] | The i-th subelement of the current element. |
| .. | the parent of the current element. |

 When [XPath](#xpath-property-json-class) is set to a valid path, the following properties are updated:

- [XElement](#xelement-property-json-class)
- [XElementType](#xelementtype-property-json-class)
- [XParent](#xparent-property-json-class)
- [XText](#xtext-property-json-class)
- [XSubTree](#xsubtree-property-json-class)
- [XChildren](#xchildren-property-json-class)

[BuildDOM](#builddom-property-json-class) must be set to True before parsing the document for the [XPath](#xpath-property-json-class) functionality to be available.

**Simple JSON Document**

```text
{
  "firstlevel": {
    "one": "value",
    "two": ["first", "second"],
    "three": "value three"
  }
}
```

 **Example 1. Setting XPath:**

|  |  |
| --- | --- |
| Document root | JsonControl.XPath = "/" |
| Specific Element | JsonControl.XPath = "/json/firstlevel/one/" |
| i-th Child | JsonControl.XPath = "/json/firstlevel/two/[i]/" |

 NOTE: When using XPath notation, the root element is always referred to as "json". As in the previous examples, this means all paths will begin with "/json".

### JSONPath

 This property implements a subset of the JSONPath notation. This may be set to point to a specific element in the JSON document.

The JSONPath is a series of one or more accessors in either dot-notation

```text
$.store.book[0].title
```

 or in bracket-notation, as follows:

```text
$['store']['book'][0]['title']
```

After setting [XPath](#xpath-property-json-class), the following properties are populated:

- [XChildren](#xchildren-property-json-class)
- [XElement](#xelement-property-json-class)
- [XElementType](#xelementtype-property-json-class)
- [XSubTree](#xsubtree-property-json-class)
- [XText](#xtext-property-json-class)

 **Example 2. Setting JSONPath:**

Given the following JSON document:

```text
{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
}
```

 The following code shows several examples.

Get the first book's author:

```text
json.XPath = "$.store.book[0].author";
Console.WriteLine(json.XText);

//Output
//"Nigel Rees"
```

 Select the first book and inspect the children:

```text
json.XPath = "$.store.book[0]";
Console.WriteLine("Child Count: " + json.XChildren.Count);
Console.WriteLine(json.XChildren[1].Name + ": " + json.XChildren[1].XText);

//Output
//Child Count: 4
//author: "Nigel Rees"
```

 Get the price of the second book:

```text
json.XPath = "$['store']['book'][1]['price']";
Console.WriteLine(json.XText);

//Output
//12.99
```

 Get the second to last book's author:

```text
json.XPath = "$['store']['book'][last() - 1]['author']";
Console.WriteLine(json.XText);
Console.WriteLine(json.XPath); //Note that "last() - 1" is resolved to "3".

//Output
//"Herman Melville"
//$['store']['book'][3]['author']
```

 Display the full subtree at the current path:

```text
json.XPath = "$.store.book[0]";
Console.WriteLine(json.XSubTree);

//Output
//            {
//                "category": "reference",
//                "author": "Nigel Rees",
//                "title": "Sayings of the Century",
//                "price": 8.95
//            }
```

**Input Properties**

The class will determine the source of the input based on which properties are set.

The order in which the input properties are checked is as follows:

- [InputFile](#inputfile-property-json-class)
- [InputData](#inputdata-property-json-class)

 When a valid source is found, the search stops.

If parsing multiple documents, call [Reset](#reset-method-json-class) between documents to reset the parser.

### Writing JSON

The JSON class also can be used to create a JSON document.

The document is written to the selected output property. In addition, as the document is written, the [JSON](#json-event-json-class) event will fire. The *Text* event parameter contains the part of the document currently being written.

**Output Properties**

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

- [OutputFile](#outputfile-property-json-class)
- [OutputData](#outputdata-property-json-class): The output data are written to this property if no other destination is specified.

**Example. Writing a JSON Document:**

Writing a simple JSON document describing a pet:

```text
      Json json = new Json();
      json.OutputFile = "C:\\temp\\fido.json";
      json.StartObject();
      json.PutProperty("name", "fido", 2);
      json.PutName("previousOwners");
      json.StartArray();
      json.PutValue("Steve Widgetson", 2);
      json.PutValue("Wanda Widgetson", 2);
      json.PutValue("Randy Cooper", 2);
      json.PutValue("Linda Glover", 2);
      json.EndArray();
      json.PutProperty("weightUnit", "lbs", 2);
      json.PutProperty("weight", "62", 3);
      json.EndObject();
      json.Flush();
```

This example results in the following JSON:

```text
{
  "name": "fido",
  "previousOwners": [
    "Steve Widgetson",
    "Wanda Widgetson",
    "Randy Cooper",
    "Linda Glover"
  ],
  "weightUnit": "lbs",
  "weight": 62
}
```

When writing multiple documents, call [Reset](#reset-method-json-class) between documents to reset the writer.

### Modifying JSON

The JSON class also allows for modifying existing JSON documents. After loading a JSON document with [Parse](#parse-method-json-class) the document may be edited. The class supports inserting new values, renaming or overwriting existing values, and removing values. After editing is complete, call [Save](#save-method-json-class) to output the updated JSON document.

The following methods are applicable when modifying a JSON document:

- [InsertProperty](#insertproperty-method-json-class)
- [InsertValue](#insertvalue-method-json-class)
- [Remove](#remove-method-json-class)
- [Save](#save-method-json-class)
- [SetName](#setname-method-json-class)
- [SetValue](#setvalue-method-json-class)

When [Save](#save-method-json-class) is called, the modified JSON is written to the specified output location.

**Output Properties**

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

- [OutputFile](#outputfile-property-json-class)
- [OutputData](#outputdata-property-json-class): The output data are written to this property if no other destination is specified.

**Example 1. Inserting New Values:**

To insert new values in a JSON document, first load the existing document with [Parse](#parse-method-json-class). Next set [XPath](#xpath-property-json-class) to the sibling or parent of the data to be inserted. Call [InsertProperty](#insertproperty-method-json-class) or [InsertValue](#insertvalue-method-json-class) and pass the *ValueType* and *Position* parameters to indicate the type of data being inserted and the position.

The *ValueType* parameter of these methods specifies the type of the value. Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

The *Position* parameter of these methods specifies the position of *Value*. Possible values are as follows:

- 0 (Before the current element)
- 1 (After the current element)
- 2 (The first child of the current element)
- 3 (The last child of the current element)

For example:

Given the following JSON:

```text
{
    "store": {
        "books": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
            }
        ]
    }
}
```

Insert a new property "price" for each book:

```csharp
json.XPath = "/json/store/books/[1]";
json.InsertProperty("price", "8.95", 3, 3);  //3 - Number, 3 - Last Child

json.XPath = "/json/store/books/[2]";
json.InsertProperty("price", "12.99", 3, 3); //3 - Number, 3 - Last Child

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    }
    ]
  }
}
```

To add a new book to the array:

```csharp
json.XPath = "/json/store/books";
json.InsertValue("", 0, 3); //0 - Object, 3 - Last Child
json.XPath = "/json/store/books/[3]";
json.InsertProperty("category", "fiction", 2, 3);        //2 - String, 3 - Last Child
json.InsertProperty("author", "Herman Melville", 2, 3);  //2 - String, 3 - Last Child
json.InsertProperty("title", "Moby Dick", 2, 3);         //2 - String, 3 - Last Child
json.InsertProperty("price", "8.99", 3, 3);              //3 - Number, 3 - Last Child

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}
```

To add a new array property to each book:

```csharp
json.XPath = "/json/store/books/[1]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[1]/tags";
json.InsertValue("quotes", 2, 3);      //2 - String, 3 - Last Child
json.InsertValue("british", 2, 3);     //2 - String, 3 - Last Child

json.XPath = "/json/store/books/[2]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[2]/tags";
json.InsertValue("trilogy", 2, 3);     //2 - String, 3 - Last Child
json.InsertValue("war", 2, 3);         //2 - String, 3 - Last Child

json.XPath = "/json/store/books/[3]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[3]/tags";
json.InsertValue("classic", 2, 3);     //2 - String, 3 - Last Child
json.InsertValue("whales", 2, 3);      //2 - String, 3 - Last Child

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "tags": ["quotes", "british"],
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "tags": ["trilogy", "war"],
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}
```

**Example 2. Removing Values:**

To remove existing values, set [XPath](#xpath-property-json-class) and call the [Remove](#remove-method-json-class) method. Continuing with example 1, to remove the first book:

```csharp
json.XPath = "/json/store/books/[1]";
json.Remove();

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "tags": ["trilogy", "war"],
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}
```

To remove the "category" properties from each book:

```csharp
json.XPath = "/json/store/books/[1]/category";
json.Remove();

json.XPath = "/json/store/books/[2]/category";
json.Remove();

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "tags": ["trilogy", "war"],
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}
```

**Example 3. Updating Existing Names and Values:**

The [SetName](#setname-method-json-class) and [SetValue](#setvalue-method-json-class) methods may be used to modify existing names and values. Continuing with the preceding JSON in example 2, to rename "tags" to "meta" and update values within the array and prices:

```csharp
//Rename "tags" to "meta" for 1st book
json.XPath = "/json/store/books/[1]/tags";
json.SetName("meta");

//Update Price
json.XPath = "/json/store/books/[1]/price";
json.SetValue("13.99", 3); //3 - Number

//Rename "tags" to "meta" for 2nd book
json.XPath = "/json/store/books/[2]/tags";
json.SetName("meta");

//Update tag "whales" to "revenge"
json.XPath = "/json/store/books/[2]/meta/[2]";
json.SetValue("revenge", 2); //2 - String

//Update Price
json.XPath = "/json/store/books/[2]/price";
json.SetValue("9.99", 3); //3 - Number

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "meta": ["trilogy", "war"],
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 13.99
    },
    {
      "meta": ["classic", "revenge"],
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 9.99
    }
    ]
  }
}
```

## Property List

*The following is the full list of the properties of the class with short descriptions. Click on the links for further details.*

|  |  |
| --- | --- |
| [BuildDOM](#builddom-property-json-class) | When True, an internal object model of the JSON document is created. |
| [InputData](#inputdata-property-json-class) | This property includes the JSON data to parse. |
| [InputFile](#inputfile-property-json-class) | This property specifies the file to process. |
| [OutputData](#outputdata-property-json-class) | This property includes the output JSON after processing. |
| [OutputFile](#outputfile-property-json-class) | This is the path to a local file where the output will be written. |
| [Overwrite](#overwrite-property-json-class) | This property indicates whether or not the class should overwrite files. |
| [Validate](#validate-property-json-class) | This property controls whether documents are validated during parsing. |
| [XChildren](#xchildren-property-json-class) | This property includes a collection of child elements of the current element. |
| [XElement](#xelement-property-json-class) | This property includes the name of the current element. |
| [XElementType](#xelementtype-property-json-class) | This property indicates the data type of the current element. |
| [XErrorPath](#xerrorpath-property-json-class) | This property includes an XPath to check the server response for errors. |
| [XParent](#xparent-property-json-class) | The parent of the current element. |
| [XPath](#xpath-property-json-class) | This property provides a way to point to a specific element in the response. |
| [XSubTree](#xsubtree-property-json-class) | This property includes a snapshot of the current element in the document. |
| [XText](#xtext-property-json-class) | This property includes the text of the current element. |

## Method List

*The following is the full list of the methods of the class with short descriptions. Click on the links for further details.*

|  |  |
| --- | --- |
| [Config](#config-method-json-class) | Sets or retrieves a configuration setting. |
| [EndArray](#endarray-method-json-class) | This method writes the closing bracket of a JSON array. |
| [EndObject](#endobject-method-json-class) | This method writes the closing brace of a JSON object. |
| [Flush](#flush-method-json-class) | This method flushes the parser's or writer's buffers. |
| [HasXPath](#hasxpath-method-json-class) | This method determines whether a specific element exists in the document. |
| [InsertProperty](#insertproperty-method-json-class) | This method inserts the specified name and value at the selected position. |
| [InsertValue](#insertvalue-method-json-class) | This method inserts the specified value at the selected position. |
| [Parse](#parse-method-json-class) | This method parses the specified JSON data. |
| [PutName](#putname-method-json-class) | This method writes the name of a property. |
| [PutProperty](#putproperty-method-json-class) | This method writes a property and value. |
| [PutRaw](#putraw-method-json-class) | This method writes a raw JSON fragment. |
| [PutValue](#putvalue-method-json-class) | This method writes a value of a property. |
| [Remove](#remove-method-json-class) | This method removes the element or value set in XPath. |
| [Reset](#reset-method-json-class) | This method resets the class. |
| [Save](#save-method-json-class) | This method saves the modified JSON document. |
| [SetInputStream](#setinputstream-method-json-class) | This method sets the stream from which the class will read data to parse. |
| [SetName](#setname-method-json-class) | This method sets a new name for the element specified by XPath. |
| [SetOutputStream](#setoutputstream-method-json-class) | This method sets the stream to which the class will write the JSON. |
| [SetValue](#setvalue-method-json-class) | This method sets a new value for the element specified by XPath. |
| [StartArray](#startarray-method-json-class) | This method writes the opening bracket of a JSON array. |
| [StartObject](#startobject-method-json-class) | This event writes the opening brace of a JSON object. |
| [TryXPath](#tryxpath-method-json-class) | This method navigates to the specified XPath if it exists. |

## Event List

*The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.*

|  |  |
| --- | --- |
| [Characters](#characters-event-json-class) | This event is fired for plaintext segments of the input stream. |
| [EndDocument](#enddocument-event-json-class) | This event fires when the end of a JSON document is encountered. |
| [EndElement](#endelement-event-json-class) | This event is fired when an end-element tag is encountered. |
| [Error](#error-event-json-class) | Fired when information is available about errors during data delivery. |
| [IgnorableWhitespace](#ignorablewhitespace-event-json-class) | This event is fired when a section of ignorable whitespace is encountered. |
| [JSON](#json-event-json-class) | This event fires with the JSON data being written. |
| [StartDocument](#startdocument-event-json-class) | This event fires when the start of a new JSON document is encountered. |
| [StartElement](#startelement-event-json-class) | This event is fired when a new element is encountered in the document. |

## Config Settings

*The following is a list of config settings for the class with short descriptions. Click on the links for further details.*

|  |  |
| --- | --- |
| [CacheContent](#CacheContent) | If true, the original JSON is stored internally in a buffer. |
| [CloseInputStreamAfterProcess](#CloseInputStreamAfterProcess) | Determines whether or not the input stream is closed after processing. |
| [CloseOutputStreamAfterProcess](#CloseOutputStreamAfterProcess) | Determines whether or not the output stream is closed after processing. |
| [ElementXPath](#ElementXPath) | The XPath value for the current element in the document. |
| [EscapeForwardSlashes](#EscapeForwardSlashes) | Whether to escape forward slashes when writing a JSON object. |
| [InputFormat](#InputFormat) | Specifies the input format used in JSON streaming. |
| [PrettyPrint](#PrettyPrint) | Determines whether output is on one line or "pretty printed". |
| [RecordEndDelimiter](#RecordEndDelimiter) | The character sequence after the end of a JSON document. |
| [RecordStartDelimiter](#RecordStartDelimiter) | The character sequence before the start of a JSON document. |
| [StringProcessingOptions](#StringProcessingOptions) | Defines options to use when processing string values. |
| [XPathNotation](#XPathNotation) | Specifies the expected format when setting XPath. |
| [BuildInfo](#BuildInfo) | Information about the product's build. |
| [CodePage](#CodePage) | The system code page used for Unicode to Multibyte translations. |
| [LicenseInfo](#LicenseInfo) | Information about the current license. |
| [MaskSensitiveData](#MaskSensitiveData) | Whether sensitive data is masked in log messages. |
| [ProcessIdleEvents](#ProcessIdleEvents) | Whether the class uses its internal event loop to process events when the main thread is idle. |
| [SelectWaitMillis](#SelectWaitMillis) | The length of time in milliseconds the class will wait when DoEvents is called if there are no events to process. |
| [UseFIPSCompliantAPI](#UseFIPSCompliantAPI) | Tells the class whether or not to use FIPS certified APIs. |
| [UseInternalSecurityAPI](#UseInternalSecurityAPI) | Whether or not to use the system security libraries or an internal implementation. |

# BuildDOM Property ([JSON](#json-class) Class)

When True, an internal object model of the JSON document is created.

## Syntax

```text
ANSI (Cross Platform)
int GetBuildDOM();int SetBuildDOM(int bBuildDOM);

Unicode (Windows)
BOOL GetBuildDOM();INT SetBuildDOM(BOOL bBuildDOM);
```

## Default Value

TRUE

## Remarks

Set this property to True when you need to browse the current document through [XPath](#xpath-property-json-class).

## Data Type

Boolean

# InputData Property ([JSON](#json-class) Class)

This property includes the JSON data to parse.

## Syntax

```text
ANSI (Cross Platform)
char* GetInputData();int SetInputData(const char* lpszInputData);

Unicode (Windows)
LPWSTR GetInputData();INT SetInputData(LPCWSTR lpszInputData);
```

## Default Value

""

## Remarks

This property specifies the JSON to be processed. Set this property before calling [Parse](#parse-method-json-class).

This may be set to a complete JSON document, or partial data. When setting partial data, call [Parse](#parse-method-json-class) after each chunk of data is set. For instance:

```text
//Parse the following in chunks: { "data": 1}
json.InputData = "{ \"data\""
json.Parse();
json.InputData = ": 1}"
json.Parse();
```

**Input Properties**

The class will determine the source of the input based on which properties are set.

The order in which the input properties are checked is as follows:

- [InputFile](#inputfile-property-json-class)
- InputData

 When a valid source is found, the search stops.

## Data Type

String

# InputFile Property ([JSON](#json-class) Class)

This property specifies the file to process.

## Syntax

```text
ANSI (Cross Platform)
char* GetInputFile();int SetInputFile(const char* lpszInputFile);

Unicode (Windows)
LPWSTR GetInputFile();INT SetInputFile(LPCWSTR lpszInputFile);
```

## Default Value

""

## Remarks

This property specifies the file to be processed. Set this property to the full or relative path to the file that will be processed.

After setting this property, call [Parse](#parse-method-json-class) to parse the document.

**Input Properties**

The class will determine the source of the input based on which properties are set.

The order in which the input properties are checked is as follows:

- InputFile
- [InputData](#inputdata-property-json-class)

 When a valid source is found, the search stops.

## Data Type

String

# OutputData Property ([JSON](#json-class) Class)

This property includes the output JSON after processing.

## Syntax

```text
ANSI (Cross Platform)
char* GetOutputData();int SetOutputData(const char* lpszOutputData);

Unicode (Windows)
LPWSTR GetOutputData();INT SetOutputData(LPCWSTR lpszOutputData);
```

## Default Value

""

## Remarks

This property contains the resultant JSON after processing.

**Output Properties**

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

- [OutputFile](#outputfile-property-json-class)
- OutputData: The output data are written to this property if no other destination is specified.

## Data Type

String

# OutputFile Property ([JSON](#json-class) Class)

This is the path to a local file where the output will be written.

## Syntax

```text
ANSI (Cross Platform)
char* GetOutputFile();int SetOutputFile(const char* lpszOutputFile);

Unicode (Windows)
LPWSTR GetOutputFile();INT SetOutputFile(LPCWSTR lpszOutputFile);
```

## Default Value

""

## Remarks

This property specifies the file to which the output will be written. This may be set to an absolute or relative path.

**Output Properties**

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

- OutputFile
- [OutputData](#outputdata-property-json-class): The output data are written to this property if no other destination is specified.

## Data Type

String

# Overwrite Property ([JSON](#json-class) Class)

This property indicates whether or not the class should overwrite files.

## Syntax

```text
ANSI (Cross Platform)
int GetOverwrite();int SetOverwrite(int bOverwrite);

Unicode (Windows)
BOOL GetOverwrite();INT SetOverwrite(BOOL bOverwrite);
```

## Default Value

FALSE

## Remarks

This property indicates whether or not the class will overwrite [OutputFile](#outputfile-property-json-class). If Overwrite is False, an error will be thrown whenever [OutputFile](#outputfile-property-json-class) exists before an operation. The default value is False.

## Data Type

Boolean

# Validate Property ([JSON](#json-class) Class)

This property controls whether documents are validated during parsing.

## Syntax

```text
ANSI (Cross Platform)
int GetValidate();int SetValidate(int bValidate);

Unicode (Windows)
BOOL GetValidate();INT SetValidate(BOOL bValidate);
```

## Default Value

TRUE

## Remarks

When *true* (default), the document will be validated during parsing. To disable validation set Validate to *false*. Disabling validation may be useful in cases in which data can still be parsed even if the document is not well formed.

## Data Type

Boolean

# XChildren Property ([JSON](#json-class) Class)

This property includes a collection of child elements of the current element.

## Syntax

```text
IPWorksIoTList<IPWorksIoTJSONElement>* GetXChildren();
int SetXChildren(IPWorksIoTList<IPWorksIoTJSONElement>* val);
```

## Remarks

This property contains a collection of child elements of the current element. The elements are provided in the collection in the same order they are found in the document.

This property is not available at design time.

## Data Type

[IPWorksIoTJSONElement](#jsonelement-type)

# XElement Property ([JSON](#json-class) Class)

This property includes the name of the current element.

## Syntax

```text
ANSI (Cross Platform)
char* GetXElement();int SetXElement(const char* lpszXElement);

Unicode (Windows)
LPWSTR GetXElement();INT SetXElement(LPCWSTR lpszXElement);
```

## Default Value

""

## Remarks

This property contains the name of the current element. The current element is specified through the [XPath](#xpath-property-json-class) property.

## Data Type

String

# XElementType Property ([JSON](#json-class) Class)

This property indicates the data type of the current element.

## Syntax

```text
ANSI (Cross Platform)
int GetXElementType();

Unicode (Windows)
INT GetXElementType();
```

## Possible Values

```text
ET_OBJECT(0), ET_ARRAY(1), ET_STRING(2), ET_NUMBER(3), ET_BOOL(4), ET_NULL(5)
```

## Default Value

0

## Remarks

This property specifies the data type of the current element. After setting [XPath](#xpath-property-json-class), this property is populated. Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

NOTE: This property is not applicable when parsing a document and [BuildDOM](#builddom-property-json-class) is False.

This property is read-only.

## Data Type

Integer

# XErrorPath Property ([JSON](#json-class) Class)

This property includes an XPath to check the server response for errors.

## Syntax

```text
ANSI (Cross Platform)
char* GetXErrorPath();int SetXErrorPath(const char* lpszXErrorPath);

Unicode (Windows)
LPWSTR GetXErrorPath();INT SetXErrorPath(LPCWSTR lpszXErrorPath);
```

## Default Value

""

## Remarks

This property contains an XPath to check the server response for errors. If the XPath exists, an exception will be thrown containing the value of the element at the path.

## Data Type

String

# XParent Property ([JSON](#json-class) Class)

The parent of the current element.

## Syntax

```text
ANSI (Cross Platform)
char* GetXParent();

Unicode (Windows)
LPWSTR GetXParent();
```

## Default Value

""

## Remarks

This property contains the parent of the current element. The current element is specified via the [XPath](#xpath-property-json-class) property.

This property is read-only.

## Data Type

String

# XPath Property ([JSON](#json-class) Class)

This property provides a way to point to a specific element in the response.

## Syntax

```text
ANSI (Cross Platform)
char* GetXPath();int SetXPath(const char* lpszXPath);

Unicode (Windows)
LPWSTR GetXPath();INT SetXPath(LPCWSTR lpszXPath);
```

## Default Value

""

## Remarks

XPath may be set to navigate to specific elements within the JSON document. This will be the path to a specified value within the document. Because arrays in JSON only contain values, and no associated object name, an empty name will be used for these values. To reach an array element at position 1, the path must be set to "[1]". In addition, a root element named "json" will be added to each JSON document in the parser.

[BuildDOM](#builddom-property-json-class) must be set to True before parsing the document for the XPath functionality to be available.

The XPath property accepts both XPath and JSONPath formats. Please review the following notes on both formats.

### XPath

The path is a series of one or more element accessors separated by '/'. The path can be absolute (starting with '/') or relative to the current XPath location.

 The following are possible values for an element accessor:

|  |  |
| --- | --- |
| 'name' | A particular element name. |
| [i] | The i-th subelement of the current element. |
| .. | the parent of the current element. |

 When XPath is set to a valid path, the following properties are updated:

- [XElement](#xelement-property-json-class)
- [XElementType](#xelementtype-property-json-class)
- [XParent](#xparent-property-json-class)
- [XText](#xtext-property-json-class)
- [XSubTree](#xsubtree-property-json-class)
- [XChildren](#xchildren-property-json-class)

[BuildDOM](#builddom-property-json-class) must be set to True before parsing the document for the XPath functionality to be available.

**Simple JSON Document**

```text
{
  "firstlevel": {
    "one": "value",
    "two": ["first", "second"],
    "three": "value three"
  }
}
```

 **Example 1. Setting XPath:**

|  |  |
| --- | --- |
| Document root | JsonControl.XPath = "/" |
| Specific Element | JsonControl.XPath = "/json/firstlevel/one/" |
| i-th Child | JsonControl.XPath = "/json/firstlevel/two/[i]/" |

 NOTE: When using XPath notation, the root element is always referred to as "json". As in the previous examples, this means all paths will begin with "/json".

### JSONPath

 This property implements a subset of the JSONPath notation. This may be set to point to a specific element in the JSON document.

The JSONPath is a series of one or more accessors in either dot-notation

```text
$.store.book[0].title
```

 or in bracket-notation, as follows:

```text
$['store']['book'][0]['title']
```

After setting XPath, the following properties are populated:

- [XChildren](#xchildren-property-json-class)
- [XElement](#xelement-property-json-class)
- [XElementType](#xelementtype-property-json-class)
- [XSubTree](#xsubtree-property-json-class)
- [XText](#xtext-property-json-class)

 **Example 2. Setting JSONPath:**

Given the following JSON document:

```text
{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
}
```

 The following code shows several examples.

Get the first book's author:

```text
json.XPath = "$.store.book[0].author";
Console.WriteLine(json.XText);

//Output
//"Nigel Rees"
```

 Select the first book and inspect the children:

```text
json.XPath = "$.store.book[0]";
Console.WriteLine("Child Count: " + json.XChildren.Count);
Console.WriteLine(json.XChildren[1].Name + ": " + json.XChildren[1].XText);

//Output
//Child Count: 4
//author: "Nigel Rees"
```

 Get the price of the second book:

```text
json.XPath = "$['store']['book'][1]['price']";
Console.WriteLine(json.XText);

//Output
//12.99
```

 Get the second to last book's author:

```text
json.XPath = "$['store']['book'][last() - 1]['author']";
Console.WriteLine(json.XText);
Console.WriteLine(json.XPath); //Note that "last() - 1" is resolved to "3".

//Output
//"Herman Melville"
//$['store']['book'][3]['author']
```

 Display the full subtree at the current path:

```text
json.XPath = "$.store.book[0]";
Console.WriteLine(json.XSubTree);

//Output
//            {
//                "category": "reference",
//                "author": "Nigel Rees",
//                "title": "Sayings of the Century",
//                "price": 8.95
//            }
```

## Data Type

String

# XSubTree Property ([JSON](#json-class) Class)

This property includes a snapshot of the current element in the document.

## Syntax

```text
ANSI (Cross Platform)
char* GetXSubTree();

Unicode (Windows)
LPWSTR GetXSubTree();
```

## Default Value

""

## Remarks

The current element is specified through this property. For this property to work, you must have the [CacheContent](#CacheContent) set to True.

This property is read-only.

## Data Type

String

# XText Property ([JSON](#json-class) Class)

This property includes the text of the current element.

## Syntax

```text
ANSI (Cross Platform)
char* GetXText();int SetXText(const char* lpszXText);

Unicode (Windows)
LPWSTR GetXText();INT SetXText(LPCWSTR lpszXText);
```

## Default Value

""

## Remarks

This property contains the text of the current element. The current element is specified through the [XPath](#xpath-property-json-class) property.

## Data Type

String

# Config Method ([JSON](#json-class) Class)

Sets or retrieves a configuration setting.

## Syntax

```text
ANSI (Cross Platform)
char* Config(const char* lpszConfigurationString);

Unicode (Windows)
LPWSTR Config(LPCWSTR lpszConfigurationString);
```

## Remarks

Config is a generic method available in every class. It is used to set and retrieve [configuration settings](#config-settings-json-class) for the class.

These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these *internal properties* is provided through the Config method.

To set a configuration setting named *PROPERTY*, you must call *Config("PROPERTY=VALUE")*, where *VALUE* is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).

To read (query) the value of a [configuration setting](#config-settings-json-class), you must call *Config("PROPERTY")*. The value will be returned as a string.

## Error Handling (C++)

This method returns a String value; after it returns, call the *GetLastErrorCode()* method to obtain its result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message.

# EndArray Method ([JSON](#json-class) Class)

This method writes the closing bracket of a JSON array.

## Syntax

```text
ANSI (Cross Platform)
int EndArray();

Unicode (Windows)
INT EndArray();
```

## Remarks

This method writes the closing bracket of a JSON array to the output. An array must already have been opened by calling [StartArray](#startarray-method-json-class).

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# EndObject Method ([JSON](#json-class) Class)

This method writes the closing brace of a JSON object.

## Syntax

```text
ANSI (Cross Platform)
int EndObject();

Unicode (Windows)
INT EndObject();
```

## Remarks

This method writes the closing brace of a JSON object. An object must have been started previously by calling [StartObject](#startobject-method-json-class).

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# Flush Method ([JSON](#json-class) Class)

This method flushes the parser's or writer's buffers.

## Syntax

```text
ANSI (Cross Platform)
int Flush();

Unicode (Windows)
INT Flush();
```

## Remarks

When Flush is called, the component flushes all of its buffers, firing events as necessary.

When parsing, the end state of the JSON is checked. If [Validate](#validate-property-json-class) is also True, the parser verifies that all open elements were closed, returning an error if not.

When writing, the resultant JSON is available in one of the output properties.

**Output Properties**

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

- [OutputFile](#outputfile-property-json-class)
- [OutputData](#outputdata-property-json-class): The output data are written to this property if no other destination is specified.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# HasXPath Method ([JSON](#json-class) Class)

This method determines whether a specific element exists in the document.

## Syntax

```text
ANSI (Cross Platform)
bool HasXPath(const char* lpszXPath);

Unicode (Windows)
bool HasXPath(LPCWSTR lpszXPath);
```

## Remarks

This method determines whether a particular XPath exists within the document. This may be used to check if a path exists before setting it through [XPath](#xpath-property-json-class).

This method returns *true* if the *XPath* exists, and *false* if not.

See [XPath](#xpath-property-json-class) for details on the XPath syntax.

## Error Handling (C++)

This method returns a Boolean value; after it returns, call the *GetLastErrorCode()* method to obtain its result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message.

# InsertProperty Method ([JSON](#json-class) Class)

This method inserts the specified name and value at the selected position.

## Syntax

```text
ANSI (Cross Platform)
int InsertProperty(const char* lpszName, const char* lpszValue, int iValueType, int iPosition);

Unicode (Windows)
INT InsertProperty(LPCWSTR lpszName, LPCWSTR lpszValue, INT iValueType, INT iPosition);
```

## Remarks

This method inserts a property and its corresponding value relative to the element specified by [XPath](#xpath-property-json-class). Before calling this method, a valid JSON document must first be loaded by calling [Parse](#parse-method-json-class).

The *Name* parameter specifies the name of the property.

The *Value* parameter specifies the value of the property.

The *ValueType* parameter specifies the type of the value. Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

The *Position* parameter specifies the position of *Value* relative to the element specified by [XPath](#xpath-property-json-class). Possible values are as follows:

- 0 (Before the current element)
- 1 (After the current element)
- 2 (The first child of the current element)
- 3 (The last child of the current element)

See [Save](#save-method-json-class) for details.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# InsertValue Method ([JSON](#json-class) Class)

This method inserts the specified value at the selected position.

## Syntax

```text
ANSI (Cross Platform)
int InsertValue(const char* lpszValue, int iValueType, int iPosition);

Unicode (Windows)
INT InsertValue(LPCWSTR lpszValue, INT iValueType, INT iPosition);
```

## Remarks

This method inserts a value relative to the element specified by [XPath](#xpath-property-json-class). Before calling this method, a valid JSON document must first be loaded by calling [Parse](#parse-method-json-class).

The *Value* parameter specifies the value of the property.

The *ValueType* parameter specifies the type of the value. Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

The *Position* parameter specifies the position of *Value* relative to the element specified by [XPath](#xpath-property-json-class). Possible values are as follows:

- 0 (Before the current element)
- 1 (After the current element)
- 2 (The first child of the current element)
- 3 (The last child of the current element)

See [Save](#save-method-json-class) for details.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# Parse Method ([JSON](#json-class) Class)

This method parses the specified JSON data.

## Syntax

```text
ANSI (Cross Platform)
int Parse();

Unicode (Windows)
INT Parse();
```

## Remarks

This method parses the specified JSON data.

When parsing a document, events will fire to provide information about the parsed data. After Parse returns the document, it may be navigated by setting [XPath](#xpath-property-json-class) if [BuildDOM](#builddom-property-json-class) is True (default). If [BuildDOM](#builddom-property-json-class) is False, parsed data are accessible only through the events.

The following events will fire during parsing:

- [StartElement](#startelement-event-json-class)
- [Characters](#characters-event-json-class)
- [EndElement](#endelement-event-json-class)
- [IgnorableWhitespace](#ignorablewhitespace-event-json-class)

If [BuildDOM](#builddom-property-json-class) is True (default), [XPath](#xpath-property-json-class) may be set after this method returns. [XPath](#xpath-property-json-class) may be set to navigate to specific elements within the JSON document. This will be the path to a specified value within the document. Because arrays in JSON only contain values, and no associated object name, an empty name will be used for these values. To reach an array element at position 1, the path must be set to "[1]". In addition, a root element named "json" will be added to each JSON document in the parser.

[BuildDOM](#builddom-property-json-class) must be set to True before parsing the document for the [XPath](#xpath-property-json-class) functionality to be available.

The [XPath](#xpath-property-json-class) property accepts both XPath and JSONPath formats. Please review the following notes on both formats.

### XPath

The path is a series of one or more element accessors separated by '/'. The path can be absolute (starting with '/') or relative to the current [XPath](#xpath-property-json-class) location.

 The following are possible values for an element accessor:

|  |  |
| --- | --- |
| 'name' | A particular element name. |
| [i] | The i-th subelement of the current element. |
| .. | the parent of the current element. |

 When [XPath](#xpath-property-json-class) is set to a valid path, the following properties are updated:

- [XElement](#xelement-property-json-class)
- [XElementType](#xelementtype-property-json-class)
- [XParent](#xparent-property-json-class)
- [XText](#xtext-property-json-class)
- [XSubTree](#xsubtree-property-json-class)
- [XChildren](#xchildren-property-json-class)

[BuildDOM](#builddom-property-json-class) must be set to True before parsing the document for the [XPath](#xpath-property-json-class) functionality to be available.

**Simple JSON Document**

```text
{
  "firstlevel": {
    "one": "value",
    "two": ["first", "second"],
    "three": "value three"
  }
}
```

 **Example 1. Setting XPath:**

|  |  |
| --- | --- |
| Document root | JsonControl.XPath = "/" |
| Specific Element | JsonControl.XPath = "/json/firstlevel/one/" |
| i-th Child | JsonControl.XPath = "/json/firstlevel/two/[i]/" |

 NOTE: When using XPath notation, the root element is always referred to as "json". As in the previous examples, this means all paths will begin with "/json".

### JSONPath

 This property implements a subset of the JSONPath notation. This may be set to point to a specific element in the JSON document.

The JSONPath is a series of one or more accessors in either dot-notation

```text
$.store.book[0].title
```

 or in bracket-notation, as follows:

```text
$['store']['book'][0]['title']
```

After setting [XPath](#xpath-property-json-class), the following properties are populated:

- [XChildren](#xchildren-property-json-class)
- [XElement](#xelement-property-json-class)
- [XElementType](#xelementtype-property-json-class)
- [XSubTree](#xsubtree-property-json-class)
- [XText](#xtext-property-json-class)

 **Example 2. Setting JSONPath:**

Given the following JSON document:

```text
{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
}
```

 The following code shows several examples.

Get the first book's author:

```text
json.XPath = "$.store.book[0].author";
Console.WriteLine(json.XText);

//Output
//"Nigel Rees"
```

 Select the first book and inspect the children:

```text
json.XPath = "$.store.book[0]";
Console.WriteLine("Child Count: " + json.XChildren.Count);
Console.WriteLine(json.XChildren[1].Name + ": " + json.XChildren[1].XText);

//Output
//Child Count: 4
//author: "Nigel Rees"
```

 Get the price of the second book:

```text
json.XPath = "$['store']['book'][1]['price']";
Console.WriteLine(json.XText);

//Output
//12.99
```

 Get the second to last book's author:

```text
json.XPath = "$['store']['book'][last() - 1]['author']";
Console.WriteLine(json.XText);
Console.WriteLine(json.XPath); //Note that "last() - 1" is resolved to "3".

//Output
//"Herman Melville"
//$['store']['book'][3]['author']
```

 Display the full subtree at the current path:

```text
json.XPath = "$.store.book[0]";
Console.WriteLine(json.XSubTree);

//Output
//            {
//                "category": "reference",
//                "author": "Nigel Rees",
//                "title": "Sayings of the Century",
//                "price": 8.95
//            }
```

**Input Properties**

The class will determine the source of the input based on which properties are set.

The order in which the input properties are checked is as follows:

- [InputFile](#inputfile-property-json-class)
- [InputData](#inputdata-property-json-class)

 When a valid source is found, the search stops.

If parsing multiple documents, call [Reset](#reset-method-json-class) between documents to reset the parser.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# PutName Method ([JSON](#json-class) Class)

This method writes the name of a property.

## Syntax

```text
ANSI (Cross Platform)
int PutName(const char* lpszName);

Unicode (Windows)
INT PutName(LPCWSTR lpszName);
```

## Remarks

This method writes the name of a property. The *Name* parameter specifies the value to write.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# PutProperty Method ([JSON](#json-class) Class)

This method writes a property and value.

## Syntax

```text
ANSI (Cross Platform)
int PutProperty(const char* lpszName, const char* lpszValue, int iValueType);

Unicode (Windows)
INT PutProperty(LPCWSTR lpszName, LPCWSTR lpszValue, INT iValueType);
```

## Remarks

This method writes a property and its corresponding value to the output.

The *Name* parameter specifies the name of the property.

The *Value* parameter specifies the value of the property.

The *ValueType* parameter specifies the type of the value. Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# PutRaw Method ([JSON](#json-class) Class)

This method writes a raw JSON fragment.

## Syntax

```text
ANSI (Cross Platform)
int PutRaw(const char* lpszText);

Unicode (Windows)
INT PutRaw(LPCWSTR lpszText);
```

## Remarks

This method writes raw data to the output. This may be used to write any data of any format directly to the output.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# PutValue Method ([JSON](#json-class) Class)

This method writes a value of a property.

## Syntax

```text
ANSI (Cross Platform)
int PutValue(const char* lpszValue, int iValueType);

Unicode (Windows)
INT PutValue(LPCWSTR lpszValue, INT iValueType);
```

## Remarks

This method writes the value of a property to the output. The *Value* parameter specifies the value. The *ValueType* parameter specifies the type of data. Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# Remove Method ([JSON](#json-class) Class)

This method removes the element or value set in XPath.

## Syntax

```text
ANSI (Cross Platform)
int Remove();

Unicode (Windows)
INT Remove();
```

## Remarks

This method removes the current object at the specified [XPath](#xpath-property-json-class). This is used when editing previously loaded JSON documents.

See [Save](#save-method-json-class) for details.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# Reset Method ([JSON](#json-class) Class)

This method resets the class.

## Syntax

```text
ANSI (Cross Platform)
int Reset();

Unicode (Windows)
INT Reset();
```

## Remarks

This method resets the JSON parser.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# Save Method ([JSON](#json-class) Class)

This method saves the modified JSON document.

## Syntax

```text
ANSI (Cross Platform)
int Save();

Unicode (Windows)
INT Save();
```

## Remarks

This method saves the modified JSON data. This is used after editing a previously loaded JSON document.

After loading a JSON document with [Parse](#parse-method-json-class) the document may be edited. The class supports inserting new values, renaming or overwriting existing values, and removing values. After editing is complete, call Save to output the updated JSON document.

The following methods are applicable when modifying a JSON document:

- [InsertProperty](#insertproperty-method-json-class)
- [InsertValue](#insertvalue-method-json-class)
- [Remove](#remove-method-json-class)
- Save
- [SetName](#setname-method-json-class)
- [SetValue](#setvalue-method-json-class)

When Save is called, the modified JSON is written to the specified output location.

**Output Properties**

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

- [OutputFile](#outputfile-property-json-class)
- [OutputData](#outputdata-property-json-class): The output data are written to this property if no other destination is specified.

**Example 1. Inserting New Values:**

To insert new values in a JSON document, first load the existing document with [Parse](#parse-method-json-class). Next set [XPath](#xpath-property-json-class) to the sibling or parent of the data to be inserted. Call [InsertProperty](#insertproperty-method-json-class) or [InsertValue](#insertvalue-method-json-class) and pass the *ValueType* and *Position* parameters to indicate the type of data being inserted and the position.

The *ValueType* parameter of these methods specifies the type of the value. Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

The *Position* parameter of these methods specifies the position of *Value*. Possible values are as follows:

- 0 (Before the current element)
- 1 (After the current element)
- 2 (The first child of the current element)
- 3 (The last child of the current element)

For example:

Given the following JSON:

```text
{
    "store": {
        "books": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
            }
        ]
    }
}
```

Insert a new property "price" for each book:

```csharp
json.XPath = "/json/store/books/[1]";
json.InsertProperty("price", "8.95", 3, 3);  //3 - Number, 3 - Last Child

json.XPath = "/json/store/books/[2]";
json.InsertProperty("price", "12.99", 3, 3); //3 - Number, 3 - Last Child

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    }
    ]
  }
}
```

To add a new book to the array:

```csharp
json.XPath = "/json/store/books";
json.InsertValue("", 0, 3); //0 - Object, 3 - Last Child
json.XPath = "/json/store/books/[3]";
json.InsertProperty("category", "fiction", 2, 3);        //2 - String, 3 - Last Child
json.InsertProperty("author", "Herman Melville", 2, 3);  //2 - String, 3 - Last Child
json.InsertProperty("title", "Moby Dick", 2, 3);         //2 - String, 3 - Last Child
json.InsertProperty("price", "8.99", 3, 3);              //3 - Number, 3 - Last Child

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}
```

To add a new array property to each book:

```csharp
json.XPath = "/json/store/books/[1]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[1]/tags";
json.InsertValue("quotes", 2, 3);      //2 - String, 3 - Last Child
json.InsertValue("british", 2, 3);     //2 - String, 3 - Last Child

json.XPath = "/json/store/books/[2]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[2]/tags";
json.InsertValue("trilogy", 2, 3);     //2 - String, 3 - Last Child
json.InsertValue("war", 2, 3);         //2 - String, 3 - Last Child

json.XPath = "/json/store/books/[3]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[3]/tags";
json.InsertValue("classic", 2, 3);     //2 - String, 3 - Last Child
json.InsertValue("whales", 2, 3);      //2 - String, 3 - Last Child

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "tags": ["quotes", "british"],
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "tags": ["trilogy", "war"],
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}
```

**Example 2. Removing Values:**

To remove existing values, set [XPath](#xpath-property-json-class) and call the [Remove](#remove-method-json-class) method. Continuing with example 1, to remove the first book:

```csharp
json.XPath = "/json/store/books/[1]";
json.Remove();

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "tags": ["trilogy", "war"],
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}
```

To remove the "category" properties from each book:

```csharp
json.XPath = "/json/store/books/[1]/category";
json.Remove();

json.XPath = "/json/store/books/[2]/category";
json.Remove();

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "tags": ["trilogy", "war"],
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}
```

**Example 3. Updating Existing Names and Values:**

The [SetName](#setname-method-json-class) and [SetValue](#setvalue-method-json-class) methods may be used to modify existing names and values. Continuing with the preceding JSON in example 2, to rename "tags" to "meta" and update values within the array and prices:

```csharp
//Rename "tags" to "meta" for 1st book
json.XPath = "/json/store/books/[1]/tags";
json.SetName("meta");

//Update Price
json.XPath = "/json/store/books/[1]/price";
json.SetValue("13.99", 3); //3 - Number

//Rename "tags" to "meta" for 2nd book
json.XPath = "/json/store/books/[2]/tags";
json.SetName("meta");

//Update tag "whales" to "revenge"
json.XPath = "/json/store/books/[2]/meta/[2]";
json.SetValue("revenge", 2); //2 - String

//Update Price
json.XPath = "/json/store/books/[2]/price";
json.SetValue("9.99", 3); //3 - Number

json.Save();
```

Produces the JSON:

```text
{
  "store": {
    "books": [
    {
      "meta": ["trilogy", "war"],
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 13.99
    },
    {
      "meta": ["classic", "revenge"],
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 9.99
    }
    ]
  }
}
```

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# SetInputStream Method ([JSON](#json-class) Class)

This method sets the stream from which the class will read data to parse.

## Syntax

```text
ANSI (Cross Platform)
int SetInputStream(IPWorksIoTStream* sInputStream);

Unicode (Windows)
INT SetInputStream(IPWorksIoTStream* sInputStream);
```

## Remarks

This method specifies a stream from which data will be read when [Parse](#parse-method-json-class) is called.

**Input Properties**

The class will determine the source of the input based on which properties are set.

The order in which the input properties are checked is as follows:

- [InputFile](#inputfile-property-json-class)
- [InputData](#inputdata-property-json-class)

 When a valid source is found, the search stops.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# SetName Method ([JSON](#json-class) Class)

This method sets a new name for the element specified by XPath.

## Syntax

```text
ANSI (Cross Platform)
int SetName(const char* lpszName);

Unicode (Windows)
INT SetName(LPCWSTR lpszName);
```

## Remarks

This method sets a new name for the element specified in [XPath](#xpath-property-json-class). This is used to modify an existing JSON document.

The *Name* parameter specifies the new name of the element.

See [Save](#save-method-json-class) for details.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# SetOutputStream Method ([JSON](#json-class) Class)

This method sets the stream to which the class will write the JSON.

## Syntax

```text
ANSI (Cross Platform)
int SetOutputStream(IPWorksIoTStream* sOutputStream);

Unicode (Windows)
INT SetOutputStream(IPWorksIoTStream* sOutputStream);
```

## Remarks

This method sets the stream to which the output will be written when writing data.

**Output Properties**

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

- [OutputFile](#outputfile-property-json-class)
- [OutputData](#outputdata-property-json-class): The output data are written to this property if no other destination is specified.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# SetValue Method ([JSON](#json-class) Class)

This method sets a new value for the element specified by XPath.

## Syntax

```text
ANSI (Cross Platform)
int SetValue(const char* lpszValue, int iValueType);

Unicode (Windows)
INT SetValue(LPCWSTR lpszValue, INT iValueType);
```

## Remarks

This method sets a new value for the element specified in [XPath](#xpath-property-json-class). This is used to modify an existing JSON document.

*Value* specifies the new value.

*ValueType* specifies the type of the value. Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

See [Save](#save-method-json-class) for details.

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# StartArray Method ([JSON](#json-class) Class)

This method writes the opening bracket of a JSON array.

## Syntax

```text
ANSI (Cross Platform)
int StartArray();

Unicode (Windows)
INT StartArray();
```

## Remarks

This method writes the opening bracket of a JSON array to the output. To close the array, call [EndArray](#endarray-method-json-class).

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# StartObject Method ([JSON](#json-class) Class)

This event writes the opening brace of a JSON object.

## Syntax

```text
ANSI (Cross Platform)
int StartObject();

Unicode (Windows)
INT StartObject();
```

## Remarks

This method writes the opening brace of a JSON object to the output. To close the object, call [EndObject](#endobject-method-json-class).

## Error Handling (C++)

This method returns a result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the *GetLastErrorCode()* method after it returns.)

# TryXPath Method ([JSON](#json-class) Class)

This method navigates to the specified XPath if it exists.

## Syntax

```text
ANSI (Cross Platform)
bool TryXPath(const char* lpszxpath);

Unicode (Windows)
bool TryXPath(LPCWSTR lpszxpath);
```

## Remarks

This method will attempt to navigate to the specified *XPath* parameter if it exists within the document.

If the XPath exists, the [XPath](#xpath-property-json-class) property will be updated and this method returns *true*.

If the XPath does not exist, the [XPath](#xpath-property-json-class) property is not updated and this method returns *false*.

## Error Handling (C++)

This method returns a Boolean value; after it returns, call the *GetLastErrorCode()* method to obtain its result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message.

# Characters Event ([JSON](#json-class) Class)

This event is fired for plaintext segments of the input stream.

## Syntax

```text
ANSI (Cross Platform)
virtual int FireCharacters(JSONCharactersEventParams *e);
typedef struct {  const char *Text;
  int reserved;
} JSONCharactersEventParams;

Unicode (Windows)
virtual INT FireCharacters(JSONCharactersEventParams *e);
typedef struct {  LPCWSTR Text;
  INT reserved;
} JSONCharactersEventParams;
```

## Remarks

The Characters event provides the plaintext content of the JSON document (i.e., the text inside the elements). The text is provided through the *Text* parameter.

The text includes white space as well as end-of-line characters, except for ignorable whitespace, which is fired through the [IgnorableWhitespace](#ignorablewhitespace-event-json-class) event.

# EndDocument Event ([JSON](#json-class) Class)

This event fires when the end of a JSON document is encountered.

## Syntax

```text
ANSI (Cross Platform)
virtual int FireEndDocument(JSONEndDocumentEventParams *e);
typedef struct {
  int reserved;
} JSONEndDocumentEventParams;

Unicode (Windows)
virtual INT FireEndDocument(JSONEndDocumentEventParams *e);
typedef struct {
  INT reserved;
} JSONEndDocumentEventParams;
```

## Remarks

This event fires when parsing of a JSON document ends. This event may fire multiple times if [InputFormat](#InputFormat) is set to a value that accepts multiple JSON documents.

# EndElement Event ([JSON](#json-class) Class)

This event is fired when an end-element tag is encountered.

## Syntax

```text
ANSI (Cross Platform)
virtual int FireEndElement(JSONEndElementEventParams *e);
typedef struct {  const char *Element;
  int reserved;
} JSONEndElementEventParams;

Unicode (Windows)
virtual INT FireEndElement(JSONEndElementEventParams *e);
typedef struct {  LPCWSTR Element;
  INT reserved;
} JSONEndElementEventParams;
```

## Remarks

The EndElement event is fired when the end of an element is found in the document.

The element name is provided by the *Element* parameter.

# Error Event ([JSON](#json-class) Class)

Fired when information is available about errors during data delivery.

## Syntax

```text
ANSI (Cross Platform)
virtual int FireError(JSONErrorEventParams *e);
typedef struct {  int ErrorCode;  const char *Description;
  int reserved;
} JSONErrorEventParams;

Unicode (Windows)
virtual INT FireError(JSONErrorEventParams *e);
typedef struct {  INT ErrorCode;  LPCWSTR Description;
  INT reserved;
} JSONErrorEventParams;
```

## Remarks

The Error event is fired in case of exceptional conditions during message processing. Normally the class fails with an error.

The *ErrorCode* parameter contains an error code, and the *Description* parameter contains a textual description of the error. For a list of valid error codes and their descriptions, please refer to the [Error Codes](#trappable-errors-json-class) section.

# IgnorableWhitespace Event ([JSON](#json-class) Class)

This event is fired when a section of ignorable whitespace is encountered.

## Syntax

```text
ANSI (Cross Platform)
virtual int FireIgnorableWhitespace(JSONIgnorableWhitespaceEventParams *e);
typedef struct {  const char *Text;
  int reserved;
} JSONIgnorableWhitespaceEventParams;

Unicode (Windows)
virtual INT FireIgnorableWhitespace(JSONIgnorableWhitespaceEventParams *e);
typedef struct {  LPCWSTR Text;
  INT reserved;
} JSONIgnorableWhitespaceEventParams;
```

## Remarks

The ignorable whitespace section is provided by the *Text* parameter.

# JSON Event ([JSON](#json-class) Class)

This event fires with the JSON data being written.

## Syntax

```text
ANSI (Cross Platform)
virtual int FireJSON(JSONJSONEventParams *e);
typedef struct {  const char *Text;
  int reserved;
} JSONJSONEventParams;

Unicode (Windows)
virtual INT FireJSON(JSONJSONEventParams *e);
typedef struct {  LPCWSTR Text;
  INT reserved;
} JSONJSONEventParams;
```

## Remarks

This event fires when output data are written.

*Text* contains the JSON data currently being written.

# StartDocument Event ([JSON](#json-class) Class)

This event fires when the start of a new JSON document is encountered.

## Syntax

```text
ANSI (Cross Platform)
virtual int FireStartDocument(JSONStartDocumentEventParams *e);
typedef struct {
  int reserved;
} JSONStartDocumentEventParams;

Unicode (Windows)
virtual INT FireStartDocument(JSONStartDocumentEventParams *e);
typedef struct {
  INT reserved;
} JSONStartDocumentEventParams;
```

## Remarks

This event fires when parsing of a JSON document begins. This event may fire multiple times if [InputFormat](#InputFormat) is set to a value that accepts multiple JSON documents.

# StartElement Event ([JSON](#json-class) Class)

This event is fired when a new element is encountered in the document.

## Syntax

```text
ANSI (Cross Platform)
virtual int FireStartElement(JSONStartElementEventParams *e);
typedef struct {  const char *Element;
  int reserved;
} JSONStartElementEventParams;

Unicode (Windows)
virtual INT FireStartElement(JSONStartElementEventParams *e);
typedef struct {  LPCWSTR Element;
  INT reserved;
} JSONStartElementEventParams;
```

## Remarks

The StartElement event is fired when a new element is found in the document.

The element name is provided through the *Element* parameter.

# JSONElement Type

This type describes an element contained within the JSON document.

## Syntax

 *IPWorksIoTJSONElement* (declared in *ipworksiot.h*)

## Remarks

This type describes a JSON element.

The elements are inserted into the array in the same order they are found in the document.

The following fields are available:

- [ElementType](#JSONElement_f_ElementType)

- [Name](#JSONElement_f_Name)

- [XText](#JSONElement_f_XText)

## Fields

 **ElementType** *int (read-only)*
*Default Value: 0*

The [ElementType](#JSONElement_f_ElementType) field indicates the data type of the element.

Possible values are as follows:

- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)

 **Name** *char* (read-only)*
*Default Value: ""*

The [Name](#JSONElement_f_Name) field provides the name of the element. For elements within an array, the [Name](#JSONElement_f_Name) field will be empty.

 **XText** *char* (read-only)*
*Default Value: ""*

This field contains the text of the element.

## Constructors

```text
JSONElement()
```

# IPWorksIoTList Type

## Syntax

 *IPWorksIoTList<T>* (declared in *ipworksiot.h*)

## Remarks

 *IPWorksIoTList* is a generic class that is used to hold a collection of objects of type *T*, where *T* is one of the custom types supported by the JSON class.

```text
int GetCount() {}
```

```text
int SetCount(int count) {}
```

```text
T* Get(int index) {}
```

```text
T* Set(int index, T* value) {}
```

|  |  |
| --- | --- |
| Methods |  |
| GetCount | This method returns the current size of the collection. |
| SetCount | This method sets the size of the collection. This method returns 0 if setting the size was successful; or -1 if the collection is ReadOnly. When adding additional objects to a collection call this method to specify the new size. Increasing the size of the collection preserves existing objects in the collection. |
| Get | This method gets the item at the specified position. The index parameter specifies the index of the item in the collection. This method returns NULL if an invalid index is specified. |
| Set | This method sets the item at the specified position. The index parameter specifies the index of the item in the collection that is being set. This method returns -1 if an invalid index is specified. Note: Objects created using the new operator must be freed using the delete operator; they will not be automatically freed by the class. |

# IPWorksIoTStream Type

## Syntax

 *IPWorksIoTStream* (declared in *ipworksiot.h*)

## Remarks

 The JSON class includes one or more API members that take a stream object as a parameter. To use such API members, create a concrete class that implements the IPWorksIoTStream interface and pass the JSON class an instance of that concrete class.

 When implementing the IPWorksIoTStream interface's properties and methods, they must behave as described below. If the concrete class's implementation does not behave as expected, undefined behavior may occur.

```text
bool CanRead() { return true; }
```

```text
bool CanSeek() { return true; }
```

```text
bool CanWrite() { return true; }
```

```text
int64 GetLength() = 0;
```

```text
void Close() {}
```

```text
int Flush() { return 0; }
```

```text
int Read(void* buffer, int count) = 0;
```

```text
int64 Seek(int64 offset, int seekOrigin) = 0;
```

```text
int Write(const void* buffer, int count) = 0;
```

|  |  |
| --- | --- |
| Properties |  |
| CanRead | Whether the stream supports reading. |
| CanSeek | Whether the stream supports seeking. |
| CanWrite | Whether the stream supports writing. |
| Length | Gets the length of the stream, in bytes. |
| Methods |  |
| Close | Closes the stream, releasing all resources currently allocated for it. This method is called automatically when an IPWorksIoTStream object is deleted. |
| Flush | Forces all data held by the stream's buffers to be written out to storage. Must return 0 if flushing is successful; or -1 if an error occurs or the stream is closed. If the stream does not support writing, this method must do nothing and return 0. |
| Read | Reads a sequence of bytes from the stream and advances the current position within the stream by the number of bytes read. Buffer specifies the buffer to populate with data from the stream. Count specifies the number of bytes that should be read from the stream. Must return the total number of bytes read into Buffer; this may be less than Count if that many bytes are not currently available, or 0 if the end of the stream has been reached. Must return -1 if an error occurs, if reading is not supported, or if the stream is closed. |
| Seek | Sets the current position within the stream based on a particular point of origin. Offset specifies the offset in the stream to seek to, relative to SeekOrigin. Valid values for SeekOrigin are: 0: Seek from beginning. 1: Seek from current position. 2: Seek from end. Must return the new position within the stream; or -1 if an error occurs, if seeking is not supported, or if the stream is closed (however, see note below). If -1 is returned, the current position within the stream must remain unchanged. Note: If the stream is not closed, it must always be possible to call this method with an Offset of 0 and a SeekOrigin of 1 to obtain the current position within the stream, even if seeking is not otherwise supported. |
| Write | Writes a sequence of bytes to the stream and advances the current position within the stream by the number of bytes written. Buffer specifies the buffer with data to write to the stream. Count specifies the number of bytes that should be written to the stream. Must return the total number of bytes written to the stream; this may be less than Count if that many bytes could not be written. Must return -1 if an error occurs, if writing is not supported, or if the stream is closed. |

# Config Settings ([JSON](#json-class) Class)

 The class accepts one or more of the following *configuration settings*. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these *internal properties* is provided through the [Config](#config-method-json-class) method.

### JSON Config Settings

**CacheContent**: If true, the original JSON is stored internally in a buffer.This configuration setting controls whether the class retains the entire original JSON data in memory (default: *true*). The cached data is used by the [XSubTree](#xsubtree-property-json-class) property to return position-based subtrees from the original JSON. When CacheContents is disabled, this cached data is cleared to reduce memory usage when processing large JSON files, and XSubTree always returns an empty string as a result. Other X* properties rely on the internal [BuildDOM](#builddom-property-json-class) representation and are not affected by this setting.

**CloseInputStreamAfterProcess**: Determines whether or not the input stream is closed after processing.This configuration setting determines whether or not the input stream set by [SetInputStream](#setinputstream-method-json-class) is closed after processing is complete. The default value is True.

**CloseOutputStreamAfterProcess**: Determines whether or not the output stream is closed after processing.This configuration setting determines whether or not the output stream set by [SetOutputStream](#setoutputstream-method-json-class) is closed after processing is complete. The default value is True.

**ElementXPath**: The XPath value for the current element in the document.This configuration setting holds the current XPath value when the document is parsed. When queried from inside the [StartElement](#startelement-event-json-class) event, the corresponding element's XPath value will be returned. For instance:

```csharp
string elementXPath = json.Config("ElementXPath");
```

NOTE: The [BuildDOM](#builddom-property-json-class) property must be set to *False*.

**EscapeForwardSlashes**: Whether to escape forward slashes when writing a JSON object.This configuration setting specifies whether forward slashes (*/*) are escaped when creating a JSON object using the class. This does not affect parsing of JSON. It is applicable only when JSON values are written.

**InputFormat**: Specifies the input format used in JSON streaming.This configuration setting specifies how JSON documents are formatted as they are input to the class. This setting is designed for use when data are provided via JSON streaming. This means multiple documents may be parsed by the class. This setting is applicable only when [BuildDOM](#builddom-property-json-class) is set to False. Possible values are as follows:

| Value | Description |
| --- | --- |
| 0 (None - default) | Only a single JSON document is expected. Use this when a single JSON document is being parsed (most cases). |
| 1 (Line Delimited) | Multiple documents are separated by carriage return (CR), line feed (LF), or CRLF character sequences. |
| 2 (Record Separated) | A defined start and end delimiter separate documents. See [RecordStartDelimiter](#RecordStartDelimiter) and [RecordEndDelimiter](#RecordEndDelimiter). |
| 3 (Concatenated) | New documents begin immediately after the previous documents end; no characters or delimiters separate the documents. |

**PrettyPrint**: Determines whether output is on one line or "pretty printed".The value of this configuration setting determines whether output is generated as a single line of JSON or as multiple "pretty printed" lines. The following example code, provides a better understanding of this configuration setting:

```csharp
json.Config("PrettyPrint=true"); // false
json.StartObject();
json.PutName("data");
json.StartObject();
json.PutProperty("id", "3", 3);
json.PutProperty("first_name", "Emma", 2);
json.PutProperty("last_name", "Wong", 2);
json.PutProperty("avatar", "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg", 2);
json.EndObject();
json.EndObject();
json.Flush();
Console.WriteLine(json.OutputData);
```

 With PrettyPrint set to False (the default), the output would look like this:

```text
{"data":{"id":3,"first_name":"Emma","last_name":"Wong","avatar":"https:\/\/s3.amazonaws.com\/uifaces\/faces\/twitter\/olegpogodaev\/128.jpg"}}
```

 With PrettyPrint set to True, the output instead would look like this:

```text
{
  "data": {
    "id": 3,
    "first_name": "Emma",
    "last_name": "Wong",
    "avatar": "https:\/\/s3.amazonaws.com\/uifaces\/faces\/twitter\/olegpogodaev\/128.jpg"
  }
}
```

 The default value is False.

**RecordEndDelimiter**: The character sequence after the end of a JSON document.This configuration setting is used in conjunction with [InputFormat](#InputFormat) to specify the character sequence that is expected after the end of a JSON document.

**RecordStartDelimiter**: The character sequence before the start of a JSON document.This configuration setting is used in conjunction with [InputFormat](#InputFormat) to specify the character sequence that is expected before the start of a JSON document.

**StringProcessingOptions**: Defines options to use when processing string values.This configuration setting determines what additional processing is performed on string values during parsing. By default, no additional processing is performed and the string is returned as is from the document. Strings also may be unquoted, unescaped, or both. Possible values follow:

|  |  |
| --- | --- |
| 0 (none - default) | No additional processing is performed. |
| 1 (unquote) | Strings are unquoted. |
| 2 (unescape) | Any escaped sequences are unescaped. |
| 3 (unquote and unescape) | Values are both unquoted and unescaped. |

 For instance, given the JSON element:

```text
"example" : "value\ntest"
```

 The following table shows the resulting value for the XText of the element:

```text
"value\ntest"
```

```text
value\ntest
```

```text
"value
test"
```

```text
value
test
```

| StringProcessingOption | Output |
| --- | --- |
| 0 (none) |  |
| 1 (unquote) |  |
| 2 (unescape) |  |
| 3 (unquote and unescape) |  |

**XPathNotation**: Specifies the expected format when setting XPath.This configuration setting optionally specifies the expected input format when setting [XPath](#xpath-property-json-class). Possible values follow:

- 0 (Auto - default)
- 1 (XPath)
- 2 (JSONPath)

 In most cases, the default of 0 (Auto) is sufficient. The class will determine whether the path value is in XPath or JSONPath format automatically. If desired, the type may be explicitly set to either XPath or JSONPath using the values above.

### Base Config Settings

**BuildInfo**: Information about the product's build.When queried, this setting will return a string containing information about the product's build.

**CodePage**: The system code page used for Unicode to Multibyte translations.The default code page is Unicode UTF-8 (65001).

The following is a list of valid code page identifiers:

|  |  |
| --- | --- |
| Identifier | Name |
| 037 | IBM EBCDIC - U.S./Canada |
| 437 | OEM - United States |
| 500 | IBM EBCDIC - International |
| 708 | Arabic - ASMO 708 |
| 709 | Arabic - ASMO 449+, BCON V4 |
| 710 | Arabic - Transparent Arabic |
| 720 | Arabic - Transparent ASMO |
| 737 | OEM - Greek (formerly 437G) |
| 775 | OEM - Baltic |
| 850 | OEM - Multilingual Latin I |
| 852 | OEM - Latin II |
| 855 | OEM - Cyrillic (primarily Russian) |
| 857 | OEM - Turkish |
| 858 | OEM - Multilingual Latin I + Euro symbol |
| 860 | OEM - Portuguese |
| 861 | OEM - Icelandic |
| 862 | OEM - Hebrew |
| 863 | OEM - Canadian-French |
| 864 | OEM - Arabic |
| 865 | OEM - Nordic |
| 866 | OEM - Russian |
| 869 | OEM - Modern Greek |
| 870 | IBM EBCDIC - Multilingual/ROECE (Latin-2) |
| 874 | ANSI/OEM - Thai (same as 28605, ISO 8859-15) |
| 875 | IBM EBCDIC - Modern Greek |
| 932 | ANSI/OEM - Japanese, Shift-JIS |
| 936 | ANSI/OEM - Simplified Chinese (PRC, Singapore) |
| 949 | ANSI/OEM - Korean (Unified Hangul Code) |
| 950 | ANSI/OEM - Traditional Chinese (Taiwan; Hong Kong SAR, PRC) |
| 1026 | IBM EBCDIC - Turkish (Latin-5) |
| 1047 | IBM EBCDIC - Latin 1/Open System |
| 1140 | IBM EBCDIC - U.S./Canada (037 + Euro symbol) |
| 1141 | IBM EBCDIC - Germany (20273 + Euro symbol) |
| 1142 | IBM EBCDIC - Denmark/Norway (20277 + Euro symbol) |
| 1143 | IBM EBCDIC - Finland/Sweden (20278 + Euro symbol) |
| 1144 | IBM EBCDIC - Italy (20280 + Euro symbol) |
| 1145 | IBM EBCDIC - Latin America/Spain (20284 + Euro symbol) |
| 1146 | IBM EBCDIC - United Kingdom (20285 + Euro symbol) |
| 1147 | IBM EBCDIC - France (20297 + Euro symbol) |
| 1148 | IBM EBCDIC - International (500 + Euro symbol) |
| 1149 | IBM EBCDIC - Icelandic (20871 + Euro symbol) |
| 1200 | Unicode UCS-2 Little-Endian (BMP of ISO 10646) |
| 1201 | Unicode UCS-2 Big-Endian |
| 1250 | ANSI - Central European |
| 1251 | ANSI - Cyrillic |
| 1252 | ANSI - Latin I |
| 1253 | ANSI - Greek |
| 1254 | ANSI - Turkish |
| 1255 | ANSI - Hebrew |
| 1256 | ANSI - Arabic |
| 1257 | ANSI - Baltic |
| 1258 | ANSI/OEM - Vietnamese |
| 1361 | Korean (Johab) |
| 10000 | MAC - Roman |
| 10001 | MAC - Japanese |
| 10002 | MAC - Traditional Chinese (Big5) |
| 10003 | MAC - Korean |
| 10004 | MAC - Arabic |
| 10005 | MAC - Hebrew |
| 10006 | MAC - Greek I |
| 10007 | MAC - Cyrillic |
| 10008 | MAC - Simplified Chinese (GB 2312) |
| 10010 | MAC - Romania |
| 10017 | MAC - Ukraine |
| 10021 | MAC - Thai |
| 10029 | MAC - Latin II |
| 10079 | MAC - Icelandic |
| 10081 | MAC - Turkish |
| 10082 | MAC - Croatia |
| 12000 | Unicode UCS-4 Little-Endian |
| 12001 | Unicode UCS-4 Big-Endian |
| 20000 | CNS - Taiwan |
| 20001 | TCA - Taiwan |
| 20002 | Eten - Taiwan |
| 20003 | IBM5550 - Taiwan |
| 20004 | TeleText - Taiwan |
| 20005 | Wang - Taiwan |
| 20105 | IA5 IRV International Alphabet No. 5 (7-bit) |
| 20106 | IA5 German (7-bit) |
| 20107 | IA5 Swedish (7-bit) |
| 20108 | IA5 Norwegian (7-bit) |
| 20127 | US-ASCII (7-bit) |
| 20261 | T.61 |
| 20269 | ISO 6937 Non-Spacing Accent |
| 20273 | IBM EBCDIC - Germany |
| 20277 | IBM EBCDIC - Denmark/Norway |
| 20278 | IBM EBCDIC - Finland/Sweden |
| 20280 | IBM EBCDIC - Italy |
| 20284 | IBM EBCDIC - Latin America/Spain |
| 20285 | IBM EBCDIC - United Kingdom |
| 20290 | IBM EBCDIC - Japanese Katakana Extended |
| 20297 | IBM EBCDIC - France |
| 20420 | IBM EBCDIC - Arabic |
| 20423 | IBM EBCDIC - Greek |
| 20424 | IBM EBCDIC - Hebrew |
| 20833 | IBM EBCDIC - Korean Extended |
| 20838 | IBM EBCDIC - Thai |
| 20866 | Russian - KOI8-R |
| 20871 | IBM EBCDIC - Icelandic |
| 20880 | IBM EBCDIC - Cyrillic (Russian) |
| 20905 | IBM EBCDIC - Turkish |
| 20924 | IBM EBCDIC - Latin-1/Open System (1047 + Euro symbol) |
| 20932 | JIS X 0208-1990 & 0121-1990 |
| 20936 | Simplified Chinese (GB2312) |
| 21025 | IBM EBCDIC - Cyrillic (Serbian, Bulgarian) |
| 21027 | Extended Alpha Lowercase |
| 21866 | Ukrainian (KOI8-U) |
| 28591 | ISO 8859-1 Latin I |
| 28592 | ISO 8859-2 Central Europe |
| 28593 | ISO 8859-3 Latin 3 |
| 28594 | ISO 8859-4 Baltic |
| 28595 | ISO 8859-5 Cyrillic |
| 28596 | ISO 8859-6 Arabic |
| 28597 | ISO 8859-7 Greek |
| 28598 | ISO 8859-8 Hebrew |
| 28599 | ISO 8859-9 Latin 5 |
| 28605 | ISO 8859-15 Latin 9 |
| 29001 | Europa 3 |
| 38598 | ISO 8859-8 Hebrew |
| 50220 | ISO 2022 Japanese with no halfwidth Katakana |
| 50221 | ISO 2022 Japanese with halfwidth Katakana |
| 50222 | ISO 2022 Japanese JIS X 0201-1989 |
| 50225 | ISO 2022 Korean |
| 50227 | ISO 2022 Simplified Chinese |
| 50229 | ISO 2022 Traditional Chinese |
| 50930 | Japanese (Katakana) Extended |
| 50931 | US/Canada and Japanese |
| 50933 | Korean Extended and Korean |
| 50935 | Simplified Chinese Extended and Simplified Chinese |
| 50936 | Simplified Chinese |
| 50937 | US/Canada and Traditional Chinese |
| 50939 | Japanese (Latin) Extended and Japanese |
| 51932 | EUC - Japanese |
| 51936 | EUC - Simplified Chinese |
| 51949 | EUC - Korean |
| 51950 | EUC - Traditional Chinese |
| 52936 | HZ-GB2312 Simplified Chinese |
| 54936 | Windows XP: GB18030 Simplified Chinese (4 Byte) |
| 57002 | ISCII Devanagari |
| 57003 | ISCII Bengali |
| 57004 | ISCII Tamil |
| 57005 | ISCII Telugu |
| 57006 | ISCII Assamese |
| 57007 | ISCII Oriya |
| 57008 | ISCII Kannada |
| 57009 | ISCII Malayalam |
| 57010 | ISCII Gujarati |
| 57011 | ISCII Punjabi |
| 65000 | Unicode UTF-7 |
| 65001 | Unicode UTF-8 |

 The following is a list of valid code page identifiers for Mac OS only:

|  |  |
| --- | --- |
| Identifier | Name |
| 1 | ASCII |
| 2 | NEXTSTEP |
| 3 | JapaneseEUC |
| 4 | UTF8 |
| 5 | ISOLatin1 |
| 6 | Symbol |
| 7 | NonLossyASCII |
| 8 | ShiftJIS |
| 9 | ISOLatin2 |
| 10 | Unicode |
| 11 | WindowsCP1251 |
| 12 | WindowsCP1252 |
| 13 | WindowsCP1253 |
| 14 | WindowsCP1254 |
| 15 | WindowsCP1250 |
| 21 | ISO2022JP |
| 30 | MacOSRoman |
| 10 | UTF16String |
| 0x90000100 | UTF16BigEndian |
| 0x94000100 | UTF16LittleEndian |
| 0x8c000100 | UTF32String |
| 0x98000100 | UTF32BigEndian |
| 0x9c000100 | UTF32LittleEndian |
| 65536 | Proprietary |

**LicenseInfo**: Information about the current license.When queried, this setting will return a string containing information about the license this instance of a class is using. It will return the following information:

- Product: The product the license is for.
- Product Key: The key the license was generated from.
- License Source: Where the license was found (e.g., RuntimeLicense, License File).
- License Type: The type of license installed (e.g., Royalty Free, Single Server).
- Last Valid Build: The last valid build number for which the license will work.

**MaskSensitiveData**: Whether sensitive data is masked in log messages.In certain circumstances it may be beneficial to mask sensitive data, like passwords, in log messages. Set this to *true* to mask sensitive data. The default is *true*.

**ProcessIdleEvents**: Whether the class uses its internal event loop to process events when the main thread is idle.If set to False, the class will not fire internal idle events. Set this to False to use the class in a background thread on Mac OS. By default, this setting is True.

**SelectWaitMillis**: The length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.If there are no events to process when DoEvents is called, the class will wait for the amount of time specified here before returning. The default value is 20.

**UseFIPSCompliantAPI**: Tells the class whether or not to use FIPS certified APIs.When set to *true*, the class will utilize the underlying operating system's certified APIs. Java editions, regardless of OS, utilize Bouncy Castle Federal Information Processing Standards (FIPS), while all other Windows editions make use of Microsoft security libraries.

On Linux, the C++ edition requires installation of the FIPS-enabled OpenSSL library. The OpenSSL FIPS provider version must be at least 3.0.0. For additional information and instructions regarding the installation and activation of the FIPS-enabled OpenSSL library, please refer to the following link: [https://github.com/openssl/openssl/blob/master/README-FIPS.md](https://github.com/openssl/openssl/blob/master/README-FIPS.md)

To ensure the class utilizes the FIPS-enabled OpenSSL library, the obfuscated source code should first be compiled with OpenSSL enabled, as described in the Supported Platforms section. Additionally, the FIPS module should be enabled and active. If the obfuscated source code is not compiled as mentioned, or the FIPS module is inactive, the class will throw an appropriate error assuming FIPS mode is enabled.

FIPS mode can be enabled by setting the *UseFIPSCompliantAPI* configuration setting to *true*. This is a static setting that applies to all instances of all classes of the toolkit within the process. It is recommended to enable or disable this setting once before the component has been used to establish a connection. Enabling FIPS while an instance of the component is active and connected may result in unexpected behavior.

For more details, please see the [FIPS 140-2 Compliance](https://www.nsoftware.com/kb/articles/fips.rst) article.

NOTE: This setting is applicable only on Windows.

NOTE: Enabling FIPS compliance requires a special license; please contact [sales@nsoftware.com](mailto:sales@nsoftware.com) for details.

**UseInternalSecurityAPI**: Whether or not to use the system security libraries or an internal implementation. When set to *false*, the class will use the system security libraries by default to perform cryptographic functions where applicable.

Setting this configuration setting to *true* tells the class to use the internal implementation instead of using the system security libraries.

 On Windows, this setting is set to *false* by default. On Linux/macOS, this setting is set to *true* by default.

 To use the system security libraries for Linux, OpenSSL support must be enabled. For more information on how to enable OpenSSL, please refer to the [OpenSSL Notes](platforms.md) section.

# Trappable Errors ([JSON](#json-class) Class)

## Error Handling (C++)

Call the *GetLastErrorCode()* method to obtain the last called method's result code; *0* indicates success, while a non-zero error code indicates that this method encountered an error during its execution. Known error codes are listed below. If an error occurs, the *GetLastError()* method can be called to retrieve the associated error message.

### JSON Errors

|  |  |
| --- | --- |
| 10231 | Unbalanced element tag. |
| 10232 | Invalid JSON markup. |
| 10233 | Invalid XPath. |
| 10234 | DOM tree unavailable (set BuildDOM to True and reparse). |

### XML Errors

|  |  |
| --- | --- |
| 101 | Invalid attribute index. |
| 102 | No attributes available. |
| 103 | Invalid namespace index. |
| 104 | No namespaces available. |
| 105 | Invalid element index. |
| 106 | No elements available. |
| 107 | Attribute does not exist. |
| 201 | Unbalanced element tag. |
| 202 | Unknown element prefix (cannot find namespace). |
| 203 | Unknown attribute prefix (cannot find namespace). |
| 204 | Invalid XML markup. |
| 205 | Invalid end state for parser. |
| 206 | Document contains unbalanced elements. |
| 207 | Invalid [XPath](#xpath-property-json-class). |
| 208 | No such child. |
| 209 | Top element does not match start of path. |
| 210 | DOM tree unavailable (set [BuildDOM](#builddom-property-json-class) to true and reparse). |
| 302 | Cannot open file. |
| 401 | Invalid XML would be generated. |
| 402 | An invalid XML name has been specified. |
