Docs

IPWorks 2022 C++ Edition

Version 22.0 [Build 8171]

JSON Class

Properties   Methods   Events   Configuration Settings   Errors  

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

Syntax

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 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 can be set to False which reduces the overhead of creating the DOM and offers a fast forward-only parsing implementation which fires events to provide the parsed data.

When parsing a document events will fire to provide information about the parsed data. After Parse returns the document may be navigated by setting XPath if BuildDOM is True (default). If BuildDOM is False parsed data is only accessible through the events.

The following events will fire during parsing:

If BuildDOM is True (default), XPath may be set after this method returns. 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. Since 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 must be set to True prior to parsing the document for the XPath functionality to be available.

The XPath property accepts both XPath and JSONPath formats. Please see notes below 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:

BuildDOM must be set to True prior to parsing the document for the XPath functionality to be available.

Simple JSON document

{
  "firstlevel": {
    "one": "value",
    "two": ["first", "second"],
    "three": "value three"
  }
}
Example (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 above 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

$.store.book[0].title
Or bracket-notation
$['store']['book'][0]['title']

After setting XPath the following properties are populated:

Examples

Given the following JSON document:

{
    "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:

json.XPath = "$.store.book[0].author"; Console.WriteLine(json.XText); //Output //"Nigel Rees" Select the first book and inspect the children:

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:

json.XPath = "$['store']['book'][1]['price']"; Console.WriteLine(json.XText); //Output //12.99 Get the second to last book's author:

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:

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:

When a valid source is found the search stops.

If parsing multiple documents call Reset between documents to reset the parser.

Writing JSON

The JSON class can also 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 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
  • OutputData: The output data is written to this property if no other destination is specified.

Example

Writing a simple JSON document describing a pet: 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:

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

When writing multiple documents call Reset 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 the document may be editted. The class supports inserting new values, renaming or overwriting existing values, and removing values. After editting is complete call Save to output the updated JSON document.

The following methods are applicable when modifying a JSON document:

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
  • OutputData: The output data is written to this property if no other destination is specified.

Inserting New Values

To insert new values in a JSON document first load the existing document with Parse. Next set XPath to the sibling or parent of the data to be inserted. Call InsertProperty or InsertValue and pass the ValueType and Position parameters to indicate the type of data being inserted and the position.

The ValueType parameter of the above methods specifies the type of the value. Possible values are:

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

The Position parameter of the above methods specifies the position of Value. Possible values are:

  • 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:

{
    "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:

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:

{
  "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:

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:

{
  "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:

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();

Producse the JSON:

{
  "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
    }
    ]
  }
}

Removing Values

To remove existing values set XPath and call the Remove method. Continuing with the example above, to remove the first book: json.XPath = "/json/store/books/[1]"; json.Remove(); json.Save();

Produces the JSON:

{
  "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: json.XPath = "/json/store/books/[1]/category"; json.Remove(); json.XPath = "/json/store/books/[2]/category"; json.Remove(); json.Save(); Produces the JSON:

{
  "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
    }
    ]
  }
}

Updating Existing Names and Values

The SetName and SetValue methods may be used to modify existing names and values. Continuing with the JSON directly above, to rename "tags" to "meta" and update values within the array and prices:

//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:

{
  "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.

BuildDOMWhen True, an internal object model of the JSON document is created.
InputDataThe JSON data to parse.
InputFileThe file to process.
OutputDataThe output JSON after processing.
OutputFileThe path to a local file where the output will be written.
OverwriteIndicates whether or not the class should overwrite files.
ValidateWhen True, the parser checks that the document consists of well-formed XML.
XChildCountThe number of records in the XChild arrays.
XChildElementTypeThe ElementType property indicates the data type of the element.
XChildNameThe Name property provides the name of the element.
XChildXTextThis property contains the text of the element.
XElementThe name of the current element.
XElementTypeIndicates the data type of the current element.
XErrorPathAn XPath to check the server response for errors.
XParentThe parent of the current element.
XPathProvides a way to point to a specific element in the response.
XSubTreeA snapshot of the current element in the document.
XTextThe 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.

ConfigSets or retrieves a configuration setting.
EndArrayWrites the closing bracket of a JSON array.
EndObjectWrites the closing brace of a JSON object.
FlushFlushes the parser's or writer's buffers.
HasXPathDetermines whether a specific element exists in the document.
InsertPropertyThis method inserts the specified name and value at the selected position.
InsertValueThis method inserts the specified value at the selected position.
ParseThis method parses the specified JSON data.
PutNameWrites the name of a property.
PutPropertyWrite a property and value.
PutRawWrites a raw JSON fragment.
PutValueWrites a value of a property.
RemoveRemoves the element or value set in XPath.
ResetResets the class.
SaveSaves the modified JSON document.
SetInputStreamSets the stream from which the class will read data to parse.
SetNameSets a new name for the element specified by XPath.
SetOutputStreamThe stream to which the class will write the JSON.
SetValueSets a new value for the element specified by XPath.
StartArrayWrites the opening bracket of a JSON array.
StartObjectWrites the opening brace of a JSON object.
TryXPathNavigates 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.

CharactersFired for plain text segments of the input stream.
EndDocumentFires when the end of a JSON document is encountered.
EndElementFired when an end-element tag is encountered.
ErrorInformation about errors during data delivery.
IgnorableWhitespaceFired when a section of ignorable whitespace is encountered.
JSONFires with the JSON data being written.
StartDocumentFires when the start of a new JSON document is encountered.
StartElementFired when a new element is encountered in the document.

Configuration Settings


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

CacheContentIf true, the original JSON is stored internally in a buffer.
CloseInputStreamAfterProcessDetermines whether or not the input stream is closed after processing.
CloseOutputStreamAfterProcessDetermines whether or not the output stream is closed after processing.
ElementXPathThe XPath value for the current element in the document.
EscapeForwardSlashesWhether to escape forward slashes when writing a JSON object.
InputFormatSpecifies the input format used in JSON streaming.
PrettyPrintDetermines whether output is on one line or "pretty printed".
RecordEndDelimiterThe character sequence after the end of a JSON document.
RecordStartDelimiterThe character sequence before the start of a JSON document.
StringProcessingOptionsDefines options to use when processing string values.
XPathNotationSpecifies the expected format when setting XPath.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

BuildDOM Property (JSON Class)

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

Syntax

ANSI (Cross Platform)
int GetBuildDOM();
int SetBuildDOM(int bBuildDOM); Unicode (Windows) BOOL GetBuildDOM();
INT SetBuildDOM(BOOL bBuildDOM);
@property (nonatomic,readwrite,assign,getter=buildDOM,setter=setBuildDOM:) BOOL buildDOM;

- (BOOL)buildDOM;
- (void)setBuildDOM:(BOOL)newBuildDOM;
int ipworks_json_getbuilddom(void* lpObj);
int ipworks_json_setbuilddom(void* lpObj, int bBuildDOM);

Default Value

TRUE

Remarks

Set this property to True when you need to browse the current document through XPath.

Data Type

Boolean

InputData Property (JSON Class)

The JSON data to parse.

Syntax

ANSI (Cross Platform)
char* GetInputData();
int SetInputData(const char* lpszInputData); Unicode (Windows) LPWSTR GetInputData();
INT SetInputData(LPCWSTR lpszInputData);
@property (nonatomic,readwrite,assign,getter=inputData,setter=setInputData:) NSString* inputData;

- (NSString*)inputData;
- (void)setInputData:(NSString*)newInputData;
char* ipworks_json_getinputdata(void* lpObj);
int ipworks_json_setinputdata(void* lpObj, const char* lpszInputData);

Default Value

""

Remarks

This property specifies the JSON to be processed. Set this property before calling Parse.

This may be set to a complete JSON document, or partial data. When setting partial data call Parse after each chunk of data is set. For instance:

//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:

When a valid source is found the search stops.

Data Type

String

InputFile Property (JSON Class)

The file to process.

Syntax

ANSI (Cross Platform)
char* GetInputFile();
int SetInputFile(const char* lpszInputFile); Unicode (Windows) LPWSTR GetInputFile();
INT SetInputFile(LPCWSTR lpszInputFile);
@property (nonatomic,readwrite,assign,getter=inputFile,setter=setInputFile:) NSString* inputFile;

- (NSString*)inputFile;
- (void)setInputFile:(NSString*)newInputFile;
char* ipworks_json_getinputfile(void* lpObj);
int ipworks_json_setinputfile(void* lpObj, const char* lpszInputFile);

Default Value

""

Remarks

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

After setting this property call Parse 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:

When a valid source is found the search stops.

Data Type

String

OutputData Property (JSON Class)

The output JSON after processing.

Syntax

ANSI (Cross Platform)
char* GetOutputData();
int SetOutputData(const char* lpszOutputData); Unicode (Windows) LPWSTR GetOutputData();
INT SetOutputData(LPCWSTR lpszOutputData);
@property (nonatomic,readwrite,assign,getter=outputData,setter=setOutputData:) NSString* outputData;

- (NSString*)outputData;
- (void)setOutputData:(NSString*)newOutputData;
char* ipworks_json_getoutputdata(void* lpObj);
int ipworks_json_setoutputdata(void* lpObj, const char* 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
  • OutputData: The output data is written to this property if no other destination is specified.

Data Type

String

OutputFile Property (JSON Class)

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

Syntax

ANSI (Cross Platform)
char* GetOutputFile();
int SetOutputFile(const char* lpszOutputFile); Unicode (Windows) LPWSTR GetOutputFile();
INT SetOutputFile(LPCWSTR lpszOutputFile);
@property (nonatomic,readwrite,assign,getter=outputFile,setter=setOutputFile:) NSString* outputFile;

- (NSString*)outputFile;
- (void)setOutputFile:(NSString*)newOutputFile;
char* ipworks_json_getoutputfile(void* lpObj);
int ipworks_json_setoutputfile(void* lpObj, const char* 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: The output data is written to this property if no other destination is specified.

Data Type

String

Overwrite Property (JSON Class)

Indicates whether or not the class should overwrite files.

Syntax

ANSI (Cross Platform)
int GetOverwrite();
int SetOverwrite(int bOverwrite); Unicode (Windows) BOOL GetOverwrite();
INT SetOverwrite(BOOL bOverwrite);
@property (nonatomic,readwrite,assign,getter=overwrite,setter=setOverwrite:) BOOL overwrite;

- (BOOL)overwrite;
- (void)setOverwrite:(BOOL)newOverwrite;
int ipworks_json_getoverwrite(void* lpObj);
int ipworks_json_setoverwrite(void* lpObj, int bOverwrite);

Default Value

FALSE

Remarks

This property indicates whether or not the class will overwrite OutputFile. If Overwrite is False, an error will be thrown whenever OutputFile exists before an operation. The default value is False.

Data Type

Boolean

Validate Property (JSON Class)

When True, the parser checks that the document consists of well-formed XML.

Syntax

ANSI (Cross Platform)
int GetValidate();
int SetValidate(int bValidate); Unicode (Windows) BOOL GetValidate();
INT SetValidate(BOOL bValidate);
@property (nonatomic,readwrite,assign,getter=validate,setter=setValidate:) BOOL validate;

- (BOOL)validate;
- (void)setValidate:(BOOL)newValidate;
int ipworks_json_getvalidate(void* lpObj);
int ipworks_json_setvalidate(void* lpObj, int bValidate);

Default Value

TRUE

Remarks

You can set Validate to False when you want to ignore XML format rules (e.g. while parsing HTML files).

Data Type

Boolean

XChildCount Property (JSON Class)

The number of records in the XChild arrays.

Syntax

ANSI (Cross Platform)
int GetXChildCount();
int SetXChildCount(int iXChildCount); Unicode (Windows) INT GetXChildCount();
INT SetXChildCount(INT iXChildCount);
@property (nonatomic,readwrite,assign,getter=XChildCount,setter=setXChildCount:) int XChildCount;

- (int)XChildCount;
- (void)setXChildCount:(int)newXChildCount;
int ipworks_json_getxchildcount(void* lpObj);
int ipworks_json_setxchildcount(void* lpObj, int iXChildCount);

Default Value

0

Remarks

This property controls the size of the following arrays:

The array indices start at 0 and end at XChildCount - 1.

This property is not available at design time.

Data Type

Integer

XChildElementType Property (JSON Class)

The ElementType property indicates the data type of the element.

Syntax

ANSI (Cross Platform)
int GetXChildElementType(int iXChildIndex);

Unicode (Windows)
INT GetXChildElementType(INT iXChildIndex);

Possible Values

ET_OBJECT(0), 
ET_ARRAY(1),
ET_STRING(2),
ET_NUMBER(3),
ET_BOOL(4),
ET_NULL(5)
- (int)XChildElementType:(int)xChildIndex;

Possible Values

ET_OBJECT(0), 
ET_ARRAY(1),
ET_STRING(2),
ET_NUMBER(3),
ET_BOOL(4),
ET_NULL(5)
int ipworks_json_getxchildelementtype(void* lpObj, int xchildindex);

Default Value

0

Remarks

The XChildElementType property indicates the data type of the element.

Possible values are:

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

The XChildIndex parameter specifies the index of the item in the array. The size of the array is controlled by the XChildCount property.

This property is read-only and not available at design time.

Data Type

Integer

XChildName Property (JSON Class)

The Name property provides the name of the element.

Syntax

ANSI (Cross Platform)
char* GetXChildName(int iXChildIndex);

Unicode (Windows)
LPWSTR GetXChildName(INT iXChildIndex);
- (NSString*)XChildName:(int)xChildIndex;
char* ipworks_json_getxchildname(void* lpObj, int xchildindex);

Default Value

""

Remarks

The XChildName property provides the name of the element. For elements within an array, the XChildName property will be empty.

The XChildIndex parameter specifies the index of the item in the array. The size of the array is controlled by the XChildCount property.

This property is read-only and not available at design time.

Data Type

String

XChildXText Property (JSON Class)

This property contains the text of the element.

Syntax

ANSI (Cross Platform)
char* GetXChildXText(int iXChildIndex);

Unicode (Windows)
LPWSTR GetXChildXText(INT iXChildIndex);
- (NSString*)XChildXText:(int)xChildIndex;
char* ipworks_json_getxchildxtext(void* lpObj, int xchildindex);

Default Value

""

Remarks

This property contains the text of the element.

The XChildIndex parameter specifies the index of the item in the array. The size of the array is controlled by the XChildCount property.

This property is read-only and not available at design time.

Data Type

String

XElement Property (JSON Class)

The name of the current element.

Syntax

ANSI (Cross Platform)
char* GetXElement();
int SetXElement(const char* lpszXElement); Unicode (Windows) LPWSTR GetXElement();
INT SetXElement(LPCWSTR lpszXElement);
@property (nonatomic,readwrite,assign,getter=XElement,setter=setXElement:) NSString* XElement;

- (NSString*)XElement;
- (void)setXElement:(NSString*)newXElement;
char* ipworks_json_getxelement(void* lpObj);
int ipworks_json_setxelement(void* lpObj, const char* lpszXElement);

Default Value

""

Remarks

This property contains the name of the current element. The current element is specified via the XPath property.

Data Type

String

XElementType Property (JSON Class)

Indicates the data type of the current element.

Syntax

ANSI (Cross Platform)
int GetXElementType();

Unicode (Windows)
INT GetXElementType();

Possible Values

ET_OBJECT(0), 
ET_ARRAY(1),
ET_STRING(2),
ET_NUMBER(3),
ET_BOOL(4),
ET_NULL(5)
@property (nonatomic,readonly,assign,getter=XElementType) int XElementType;

- (int)XElementType;

Possible Values

ET_OBJECT(0), 
ET_ARRAY(1),
ET_STRING(2),
ET_NUMBER(3),
ET_BOOL(4),
ET_NULL(5)
int ipworks_json_getxelementtype(void* lpObj);

Default Value

0

Remarks

This property specifies the data type of the current element. After setting XPath this property is populated. Possible values are:

  • 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 is False.

This property is read-only.

Data Type

Integer

XErrorPath Property (JSON Class)

An XPath to check the server response for errors.

Syntax

ANSI (Cross Platform)
char* GetXErrorPath();
int SetXErrorPath(const char* lpszXErrorPath); Unicode (Windows) LPWSTR GetXErrorPath();
INT SetXErrorPath(LPCWSTR lpszXErrorPath);
@property (nonatomic,readwrite,assign,getter=XErrorPath,setter=setXErrorPath:) NSString* XErrorPath;

- (NSString*)XErrorPath;
- (void)setXErrorPath:(NSString*)newXErrorPath;
char* ipworks_json_getxerrorpath(void* lpObj);
int ipworks_json_setxerrorpath(void* lpObj, const char* 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 Class)

The parent of the current element.

Syntax

ANSI (Cross Platform)
char* GetXParent();

Unicode (Windows)
LPWSTR GetXParent();
@property (nonatomic,readonly,assign,getter=XParent) NSString* XParent;

- (NSString*)XParent;
char* ipworks_json_getxparent(void* lpObj);

Default Value

""

Remarks

This property contains the parent of the current element. The current element is specified via the XPath property.

This property is read-only.

Data Type

String

XPath Property (JSON Class)

Provides a way to point to a specific element in the response.

Syntax

ANSI (Cross Platform)
char* GetXPath();
int SetXPath(const char* lpszXPath); Unicode (Windows) LPWSTR GetXPath();
INT SetXPath(LPCWSTR lpszXPath);
@property (nonatomic,readwrite,assign,getter=XPath,setter=setXPath:) NSString* XPath;

- (NSString*)XPath;
- (void)setXPath:(NSString*)newXPath;
char* ipworks_json_getxpath(void* lpObj);
int ipworks_json_setxpath(void* lpObj, const char* 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. Since 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 must be set to True prior to parsing the document for the XPath functionality to be available.

The XPath property accepts both XPath and JSONPath formats. Please see notes below 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:

BuildDOM must be set to True prior to parsing the document for the XPath functionality to be available.

Simple JSON document

{
  "firstlevel": {
    "one": "value",
    "two": ["first", "second"],
    "three": "value three"
  }
}
Example (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 above 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

$.store.book[0].title
Or bracket-notation
$['store']['book'][0]['title']

After setting XPath the following properties are populated:

Examples

Given the following JSON document:

{
    "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:

json.XPath = "$.store.book[0].author"; Console.WriteLine(json.XText); //Output //"Nigel Rees" Select the first book and inspect the children:

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:

json.XPath = "$['store']['book'][1]['price']"; Console.WriteLine(json.XText); //Output //12.99 Get the second to last book's author:

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:

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 Class)

A snapshot of the current element in the document.

Syntax

ANSI (Cross Platform)
char* GetXSubTree();

Unicode (Windows)
LPWSTR GetXSubTree();
@property (nonatomic,readonly,assign,getter=XSubTree) NSString* XSubTree;

- (NSString*)XSubTree;
char* ipworks_json_getxsubtree(void* lpObj);

Default Value

""

Remarks

The current element is specified via this property. In order for this property to work you must have the CacheContent set to true.

This property is read-only.

Data Type

String

XText Property (JSON Class)

The text of the current element.

Syntax

ANSI (Cross Platform)
char* GetXText();
int SetXText(const char* lpszXText); Unicode (Windows) LPWSTR GetXText();
INT SetXText(LPCWSTR lpszXText);
@property (nonatomic,readwrite,assign,getter=XText,setter=setXText:) NSString* XText;

- (NSString*)XText;
- (void)setXText:(NSString*)newXText;
char* ipworks_json_getxtext(void* lpObj);
int ipworks_json_setxtext(void* lpObj, const char* lpszXText);

Default Value

""

Remarks

This property contains the text of the current element. The current element is specified via the XPath property.

Data Type

String

Config Method (JSON Class)

Sets or retrieves a configuration setting.

Syntax

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

Unicode (Windows)
LPWSTR Config(LPCWSTR lpszConfigurationString);
- (NSString*)config:(NSString*)configurationString;
char* ipworks_json_config(void* lpObj, const char* lpszConfigurationString);

Remarks

Config is a generic method available in every class. It is used to set and retrieve configuration settings 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, 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 Class)

Writes the closing bracket of a JSON array.

Syntax

ANSI (Cross Platform)
int EndArray();

Unicode (Windows)
INT EndArray();
- (void)endArray;
int ipworks_json_endarray(void* lpObj);

Remarks

This method writes the closing bracket of a JSON array to the output. An array must already have been opened by calling StartArray.

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 Class)

Writes the closing brace of a JSON object.

Syntax

ANSI (Cross Platform)
int EndObject();

Unicode (Windows)
INT EndObject();
- (void)endObject;
int ipworks_json_endobject(void* lpObj);

Remarks

This method writes the closing brace of a JSON object. A object must have previously been started by calling StartObject.

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 Class)

Flushes the parser's or writer's buffers.

Syntax

ANSI (Cross Platform)
int Flush();

Unicode (Windows)
INT Flush();
- (void)flush;
int ipworks_json_flush(void* lpObj);

Remarks

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

When parsing, then the end state of the JSON is checked. If Validate 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
  • OutputData: The output data is 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 Class)

Determines whether a specific element exists in the document.

Syntax

ANSI (Cross Platform)
int HasXPath(const char* lpszXPath);

Unicode (Windows)
INT HasXPath(LPCWSTR lpszXPath);
- (BOOL)hasXPath:(NSString*)XPath;
int ipworks_json_hasxpath(void* lpObj, const char* 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 via XPath.

This method returns True if the xpath exists, False if not.

See XPath 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 Class)

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

Syntax

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);
- (void)insertProperty:(NSString*)name :(NSString*)value :(int)valueType :(int)position;
int ipworks_json_insertproperty(void* lpObj, const char* lpszName, const char* lpszValue, int iValueType, int iPosition);

Remarks

This method inserts a property and its corresponding value relative to the element specified by XPath. Before calling this method a valid JSON document must first be loaded by calling Parse.

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:

  • 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. Possible values are:

  • 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 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 Class)

This method inserts the specified value at the selected position.

Syntax

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

Unicode (Windows)
INT InsertValue(LPCWSTR lpszValue, INT iValueType, INT iPosition);
- (void)insertValue:(NSString*)value :(int)valueType :(int)position;
int ipworks_json_insertvalue(void* lpObj, const char* lpszValue, int iValueType, int iPosition);

Remarks

This method inserts a value relative to the element specified by XPath. Before calling this method a valid JSON document must first be loaded by calling Parse.

The Value parameter specifies the value of the property.

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

  • 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. Possible values are:

  • 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 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 Class)

This method parses the specified JSON data.

Syntax

ANSI (Cross Platform)
int Parse();

Unicode (Windows)
INT Parse();
- (void)parse;
int ipworks_json_parse(void* lpObj);

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 may be navigated by setting XPath if BuildDOM is True (default). If BuildDOM is False parsed data is only accessible through the events.

The following events will fire during parsing:

If BuildDOM is True (default), XPath may be set after this method returns. 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. Since 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 must be set to True prior to parsing the document for the XPath functionality to be available.

The XPath property accepts both XPath and JSONPath formats. Please see notes below 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:

BuildDOM must be set to True prior to parsing the document for the XPath functionality to be available.

Simple JSON document

{
  "firstlevel": {
    "one": "value",
    "two": ["first", "second"],
    "three": "value three"
  }
}
Example (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 above 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

$.store.book[0].title
Or bracket-notation
$['store']['book'][0]['title']

After setting XPath the following properties are populated:

Examples

Given the following JSON document:

{
    "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:

json.XPath = "$.store.book[0].author"; Console.WriteLine(json.XText); //Output //"Nigel Rees" Select the first book and inspect the children:

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:

json.XPath = "$['store']['book'][1]['price']"; Console.WriteLine(json.XText); //Output //12.99 Get the second to last book's author:

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:

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:

When a valid source is found the search stops.

If parsing multiple documents call Reset 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 Class)

Writes the name of a property.

Syntax

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

Unicode (Windows)
INT PutName(LPCWSTR lpszName);
- (void)putName:(NSString*)name;
int ipworks_json_putname(void* lpObj, const char* 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 Class)

Write a property and value.

Syntax

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

Unicode (Windows)
INT PutProperty(LPCWSTR lpszName, LPCWSTR lpszValue, INT iValueType);
- (void)putProperty:(NSString*)name :(NSString*)value :(int)valueType;
int ipworks_json_putproperty(void* lpObj, const char* lpszName, const char* 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:

  • 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 Class)

Writes a raw JSON fragment.

Syntax

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

Unicode (Windows)
INT PutRaw(LPCWSTR lpszText);
- (void)putRaw:(NSString*)text;
int ipworks_json_putraw(void* lpObj, const char* 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 Class)

Writes a value of a property.

Syntax

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

Unicode (Windows)
INT PutValue(LPCWSTR lpszValue, INT iValueType);
- (void)putValue:(NSString*)value :(int)valueType;
int ipworks_json_putvalue(void* lpObj, const char* 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:

  • 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 Class)

Removes the element or value set in XPath.

Syntax

ANSI (Cross Platform)
int Remove();

Unicode (Windows)
INT Remove();
- (void)remove;
int ipworks_json_remove(void* lpObj);

Remarks

This method removes the current object at the specified XPath. This is used when editing previously loaded JSON documents.

See Save 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 Class)

Resets the class.

Syntax

ANSI (Cross Platform)
int Reset();

Unicode (Windows)
INT Reset();
- (void)reset;
int ipworks_json_reset(void* lpObj);

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 Class)

Saves the modified JSON document.

Syntax

ANSI (Cross Platform)
int Save();

Unicode (Windows)
INT Save();
- (void)save;
int ipworks_json_save(void* lpObj);

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 the document may be editted. The class supports inserting new values, renaming or overwriting existing values, and removing values. After editting is complete call Save to output the updated JSON document.

The following methods are applicable when modifying a JSON document:

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
  • OutputData: The output data is written to this property if no other destination is specified.

Inserting New Values

To insert new values in a JSON document first load the existing document with Parse. Next set XPath to the sibling or parent of the data to be inserted. Call InsertProperty or InsertValue and pass the ValueType and Position parameters to indicate the type of data being inserted and the position.

The ValueType parameter of the above methods specifies the type of the value. Possible values are:

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

The Position parameter of the above methods specifies the position of Value. Possible values are:

  • 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:

{
    "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:

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:

{
  "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:

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:

{
  "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:

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();

Producse the JSON:

{
  "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
    }
    ]
  }
}

Removing Values

To remove existing values set XPath and call the Remove method. Continuing with the example above, to remove the first book: json.XPath = "/json/store/books/[1]"; json.Remove(); json.Save();

Produces the JSON:

{
  "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: json.XPath = "/json/store/books/[1]/category"; json.Remove(); json.XPath = "/json/store/books/[2]/category"; json.Remove(); json.Save(); Produces the JSON:

{
  "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
    }
    ]
  }
}

Updating Existing Names and Values

The SetName and SetValue methods may be used to modify existing names and values. Continuing with the JSON directly above, to rename "tags" to "meta" and update values within the array and prices:

//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:

{
  "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 Class)

Sets the stream from which the class will read data to parse.

Syntax

ANSI (Cross Platform)
int SetInputStream(IPWorksStream* sInputStream);

Unicode (Windows)
INT SetInputStream(IPWorksStream* sInputStream);
int ipworks_json_setinputstream(void* lpObj, IPWorksStream* sInputStream);

Remarks

This method specifies a stream from which data will be read when Parse 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:

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 Class)

Sets a new name for the element specified by XPath.

Syntax

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

Unicode (Windows)
INT SetName(LPCWSTR lpszName);
- (void)setName:(NSString*)name;
int ipworks_json_setname(void* lpObj, const char* lpszName);

Remarks

This method sets a new name for the element specified in XPath. This is used to modify an existing JSON document.

The Name parameter specifies the new name of the element.

See Save 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 Class)

The stream to which the class will write the JSON.

Syntax

ANSI (Cross Platform)
int SetOutputStream(IPWorksStream* sOutputStream);

Unicode (Windows)
INT SetOutputStream(IPWorksStream* sOutputStream);
int ipworks_json_setoutputstream(void* lpObj, IPWorksStream* sOutputStream);

Remarks

This method sets the stream to which 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
  • OutputData: The output data is 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 Class)

Sets a new value for the element specified by XPath.

Syntax

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

Unicode (Windows)
INT SetValue(LPCWSTR lpszValue, INT iValueType);
- (void)setValue:(NSString*)value :(int)valueType;
int ipworks_json_setvalue(void* lpObj, const char* lpszValue, int iValueType);

Remarks

This method sets a new value for the element specified in XPath. This is used to modify an existing JSON document.

Value specifies the new value.

ValueType specifies the type of the value. Possible values are:

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

See Save 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 Class)

Writes the opening bracket of a JSON array.

Syntax

ANSI (Cross Platform)
int StartArray();

Unicode (Windows)
INT StartArray();
- (void)startArray;
int ipworks_json_startarray(void* lpObj);

Remarks

This method writes the opening bracket of a JSON array to the output. To close the array call EndArray.

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 Class)

Writes the opening brace of a JSON object.

Syntax

ANSI (Cross Platform)
int StartObject();

Unicode (Windows)
INT StartObject();
- (void)startObject;
int ipworks_json_startobject(void* lpObj);

Remarks

This method writes the opening brace of a JSON object to the output. To close the object call EndObject.

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 Class)

Navigates to the specified XPath if it exists.

Syntax

ANSI (Cross Platform)
int TryXPath(const char* lpszxpath);

Unicode (Windows)
INT TryXPath(LPCWSTR lpszxpath);
- (BOOL)tryXPath:(NSString*)xpath;
int ipworks_json_tryxpath(void* lpObj, const char* 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 property will be updated and this method returns True.

If the XPath does not exist the XPath 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 Class)

Fired for plain text segments of the input stream.

Syntax

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;
- (void)onCharacters:(NSString*)text;
#define EID_JSON_CHARACTERS 1

virtual INT IPWORKS_CALL FireCharacters(LPSTR &lpszText);

Remarks

The Characters event provides the plain text 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 event.

EndDocument Event (JSON Class)

Fires when the end of a JSON document is encountered.

Syntax

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;
- (void)onEndDocument;
#define EID_JSON_ENDDOCUMENT 2

virtual INT IPWORKS_CALL FireEndDocument();

Remarks

This event fires when parsing of a JSON document ends. This event may fire multiple times if InputFormat is set to a value which accepts multiple JSON documents.

EndElement Event (JSON Class)

Fired when an end-element tag is encountered.

Syntax

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;
- (void)onEndElement:(NSString*)element;
#define EID_JSON_ENDELEMENT 3

virtual INT IPWORKS_CALL FireEndElement(LPSTR &lpszElement);

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 Class)

Information about errors during data delivery.

Syntax

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;
- (void)onError:(int)errorCode :(NSString*)description;
#define EID_JSON_ERROR 4

virtual INT IPWORKS_CALL FireError(INT &iErrorCode, LPSTR &lpszDescription);

Remarks

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

ErrorCode contains an error code and Description contains a textual description of the error. For a list of valid error codes and their descriptions, please refer to the Error Codes section.

IgnorableWhitespace Event (JSON Class)

Fired when a section of ignorable whitespace is encountered.

Syntax

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;
- (void)onIgnorableWhitespace:(NSString*)text;
#define EID_JSON_IGNORABLEWHITESPACE 5

virtual INT IPWORKS_CALL FireIgnorableWhitespace(LPSTR &lpszText);

Remarks

The ignorable whitespace section is provided by the Text parameter.

JSON Event (JSON Class)

Fires with the JSON data being written.

Syntax

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;
- (void)onJSON:(NSString*)text;
#define EID_JSON_JSON 6

virtual INT IPWORKS_CALL FireJSON(LPSTR &lpszText);

Remarks

This event fires when output data is written.

Text contains the JSON data currently being written.

StartDocument Event (JSON Class)

Fires when the start of a new JSON document is encountered.

Syntax

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;
- (void)onStartDocument;
#define EID_JSON_STARTDOCUMENT 7

virtual INT IPWORKS_CALL FireStartDocument();

Remarks

This event fires when parsing of a JSON document begins. This event may fire multiple times if InputFormat is set to a value which accepts multiple JSON documents.

StartElement Event (JSON Class)

Fired when a new element is encountered in the document.

Syntax

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;
- (void)onStartElement:(NSString*)element;
#define EID_JSON_STARTELEMENT 8

virtual INT IPWORKS_CALL FireStartElement(LPSTR &lpszElement);

Remarks

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

The element name is provided through the Element parameter.

IPWorksStream Type

Syntax

IPWorksStream (declared in ipworks.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 IPWorksStream interface and pass the JSON class an instance of that concrete class.

When implementing the IPWorksStream 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.

Properties

CanRead Whether the stream supports reading.

bool CanRead() { return true; }
CanSeek Whether the stream supports seeking.

bool CanSeek() { return true; }
CanWrite Whether the stream supports writing.

bool CanWrite() { return true; }
Length Gets the length of the stream, in bytes.

int64 GetLength() = 0;

Methods

Close Closes the stream, releasing all resources currently allocated for it.

void Close() {}

This method is called automatically when an IPWorksStream object is deleted.

Flush Forces all data held by the stream's buffers to be written out to storage.

int Flush() { return 0; }

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.

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

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.

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

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.

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

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.

Configuration Settings (JSON 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 method.

JSON Configuration Settings

CacheContent:   If true, the original JSON is stored internally in a buffer.

This config controls whether or not the class retains the entire original JSON data in a buffer. This is used to retain the original JSON as opposed to returning generated JSON after parsing. The default value is true.

CloseInputStreamAfterProcess:   Determines whether or not the input stream is closed after processing.

Determines whether or not the input stream set by SetInputStream is closed after processing is complete. The default value is True.

CloseOutputStreamAfterProcess:   Determines whether or not the output stream is closed after processing.

Determines whether or not the output stream set by SetOutputStream is closed after processing is complete. The default value is True.

ElementXPath:   The XPath value for the current element in the document.

This setting holds the current XPath value when the document is parsed. When queried from inside the StartElement event, the corresponding element's XPath value will be returned. For instance:

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

Note: The BuildDOM property must be set to false.

EscapeForwardSlashes:   Whether to escape forward slashes when writing a JSON object.

This setting specifies whether forward slashes (/) are escaped when creating a JSON object using the class. This does not affect parsing of JSON, only when JSON values are written.

InputFormat:   Specifies the input format used in JSON streaming.

This setting specifies how JSON documents are formatted as they are input to the class. This setting is designed for use when data is provided via JSON streaming. This means multiple documents may be parsed by the class. This setting is only applicable when BuildDOM is set to False. Possible values are:

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 Cr, Lf, or CrLf character sequences.
2 (Record Separated) A defined start and end delimiter separate documents. See RecordStartDelimiter and RecordEndDelimiter.
3 (Concatenated) New documented begin immediately after the previous documents end, there are no characters or delimiters which 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 multiple, "pretty printed" lines. For a better understanding please take the example code below: 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 be this:

{"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 would instead be this:
{
  "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 setting is used in conjunction with 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 setting is used in conjunction with 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 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 may also be unquoted, unescaped, or both. Possible values are:

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:

"example" : "value\ntest"
The following table shows the resulting value for the XText of the element.

StringProcessingOptionOutput
0 (none)
"value\ntest"
1 (unquote)
value\ntest
2 (unescape)
"value
test"
3 (unquote and unescape)
value
test

XPathNotation:   Specifies the expected format when setting XPath.

This setting optionally specifies the expected input format when setting XPath. Possible values are:

  • 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 Configuration 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:

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

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

IdentifierName
1ASCII
2NEXTSTEP
3JapaneseEUC
4UTF8
5ISOLatin1
6Symbol
7NonLossyASCII
8ShiftJIS
9ISOLatin2
10Unicode
11WindowsCP1251
12WindowsCP1252
13WindowsCP1253
14WindowsCP1254
15WindowsCP1250
21ISO2022JP
30MacOSRoman
10UTF16String
0x90000100UTF16BigEndian
0x94000100UTF16LittleEndian
0x8c000100UTF32String
0x98000100UTF32BigEndian
0x9c000100UTF32LittleEndian
65536Proprietary

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).
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.

UseInternalSecurityAPI:   Tells the class whether or not to use the system security libraries or an internal implementation.

By default the class will use the system security libraries to perform cryptographic functions. Setting this to True tells the class to use the internal implementation instead of using the system's security API.

Trappable Errors (JSON 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 (can't find namespace).
203   Unknown attribute prefix (can't find namespace).
204   Invalid XML markup.
205   Invalid end state for parser.
206   Document contains unbalanced elements.
207   Invalid XPath.
208   No such child.
209   Top element does not match start of path.
210   DOM tree unavailable (set BuildDOM to true and reparse).
302   Can't open file.
401   Invalid XML would be generated.
402   An invalid XML name has been specified.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks 2022 C++ Edition - Version 22.0 [Build 8171]