IP*Works! 2016 .NET Edition
IP*Works! 2016 .NET Edition
Questions / Feedback?

JSON Component

Properties   Methods   Events   Configuration Settings   Errors  

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

Syntax

nsoftware.IPWorks.Json

Remarks

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

Parsing JSON

The JSON component 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 component 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 component 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 component 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:

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.

Property List


The following is the full list of the properties of the component 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 component should overwrite files.
ValidateWhen True, the parser checks that the document consists of well-formed XML.
XChildrenCollection of child elements of the current element.
XCommentsA collection of comments of the current 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 component 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.
LoadSchemaLoad the JSON schema.
ParseThis method parses the specified JSON data.
PutCommentWrites a comment to the JSON document.
PutNameWrites the name of a property.
PutPropertyWrite a property and value.
PutRawWrites a raw JSON fragment.
PutValueWrites a value of a property.
RemoveRemoves the current.
ResetResets the component.
SaveSaves the JSON data.
SetInputStreamSets the stream from which the component will read data to parse.
SetOutputStreamThe stream to which the component will write the JSON.
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 component with short descriptions. Click on the links for further details.

CharactersFired for plain text segments of the input stream.
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.
StartElementFired when a new element is encountered in the document.

Configuration Settings


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

CacheContentIf true, the original JSON is stored internally in a buffer.
CharsetSpecifies the charset used when encoding data.
CloseInputStreamAfterProcessDetermines whether or not the input stream is closed after processing.
CloseOutputStreamAfterProcessDetermines whether or not the output stream is closed after processing.
PrettyPrintDetermines whether output is on one line or "pretty printed".
StringProcessingOptionsDefines options to use when processing string values.
XPathNotationSpecifies the expected format when setting XPath.
GUIAvailableTells the component whether or not a message loop is available for processing events.
UseBackgroundThreadWhether threads created by the component are background threads.
UseInternalSecurityAPITells the component whether or not to use the system security libraries or an internal implementation.

 
 
Copyright (c) 2020 /n software inc. - All rights reserved.
IP*Works! 2016 .NET Edition - Version 16.0 [Build 7353]