6.3 JSON Parsing, JSONPath & Serialization with Newtonsoft.Json
Key Takeaways
Deserialize JSON outputs a JObject by default and Deserialize JSON Array outputs a JArray; both come from the Newtonsoft.Json library used by UiPath.
Reading a missing key returns Nothing, and chaining another indexer onto it throws a NullReferenceException.
SelectToken and SelectTokens evaluate JSONPath expressions such as
$.items[?(@.sku)]; SelectToken returns Nothing instead of throwing when the path is missing.JsonConvert.SerializeObject and DeserializeObject(Of T) convert between JSON and typed .NET objects when a stable schema exists.
Queue item SpecificContent is limited to 256,000 characters, so large JSON documents belong in storage buckets.
6.3 JSON Parsing, JSONPath & Serialization with Newtonsoft.Json
Modern enterprise architectures rely heavily on RESTful web services, microservices, cloud applications, and integrations where JavaScript Object Notation (JSON) is the universal payload format. In UiPath Studio, handling REST APIs, Orchestrator Webhook payloads, and complex integration service responses requires fluent manipulation of JSON objects and arrays. This section covers the Newtonsoft.Json (Json.NET) architecture in UiPath, dynamic and strongly typed deserialization, and deep querying via JSONPath. The next section covers the Invoke Method and Invoke Code activities.
1. Architectural Foundation: JSON & Newtonsoft.Json in UiPath
In UiPath Studio, JSON processing is powered by the Newtonsoft.Json library (Json.NET), made available visually through the official UiPath.WebAPI.Activities package.
The JSON Document Object Model (DOM) Hierarchy
Json.NET models JSON data into an in-memory Document Object Model rooted in the abstract JToken class:
JToken: The abstract base class representing any JSON element (token, object, array, primitive value).JObject: Represents a JSON object—an unordered collection of key-value pairs delimited by curly braces{}. Maps to dictionaries.JArray: Represents a JSON array—an ordered collection ofJTokenelements delimited by square brackets[]. Maps to lists or arrays.JValue: Represents primitive scalar values:string,integer,float,boolean,date, ornull.JProperty: Represents a single named key-value pair ("name": value) inside aJObject.
[Newtonsoft.Json LINQ Object Hierarchy]
JToken (Abstract Base)
/ \ \
JContainer JValue JProperty
/ \
JObject JArray
Studio Visual Activities
- Deserialize JSON: Accepts a raw JSON string and outputs a
Newtonsoft.Json.Linq.JObject. Used for single payloads, status responses, and dictionary-like structures. - Deserialize JSON Array: Accepts a raw JSON string array and outputs a
Newtonsoft.Json.Linq.JArray. Used for list payloads, search results, and batch records.
2. Dynamic Traversal, Extraction, and Modification of JObject and JArray
Once deserialized, developers can navigate JSON structures dynamically using indexer notation in Assign activities or expressions.
Indexer Navigation
Accessing nested properties uses chained string keys for objects and integer indices for arrays:
' VB.NET: Accessing nested customer address details
' JSON: { "orderId": "1001", "customer": { "name": "Acme", "address": { "city": "Dallas", "zip": "75001" } } }
Dim cityName As String = jsonCustomer("customer")("address")("city").ToString()
Dim zipCode As String = jsonCustomer("customer")("address")("zip").ToString()
// C#: Accessing nested customer address details
string cityName = jsonCustomer["customer"]["address"]["city"].ToString();
string zipCode = jsonCustomer["customer"]["address"]["zip"].ToString();
Iterating Over a JArray
When a JSON payload contains a list of items, iterate over the JArray using a standard UiPath For Each activity with TypeArgument set to Newtonsoft.Json.Linq.JToken (or JObject):
' VB.NET: Iterating through an array of invoice line items
' JSON: { "items": [ { "sku": "A101", "qty": 2, "price": 45.0 }, { "sku": "B202", "qty": 1, "price": 110.0 } ] }
Dim itemsArray As JArray = CType(jsonInvoice("items"), JArray)
For Each lineItem As JToken In itemsArray
Dim sku As String = lineItem("sku").ToString()
Dim qty As Int32 = Convert.ToInt32(lineItem("qty"))
Dim price As Double = Convert.ToDouble(lineItem("price"))
Dim subtotal As Double = qty * price
Console.WriteLine("Item: " & sku & " | Subtotal: $" & subtotal.ToString("F2"))
Next
Defensive Null Handling and Key Existence
Reading a key that does not exist returns Nothing; chaining another indexer onto that result, or calling .ToString() on it, throws a System.NullReferenceException:
' VB.NET: Defensive key checking before access
If jsonInvoice("customer") IsNot Nothing AndAlso jsonInvoice("customer")("taxId") IsNot Nothing Then
Dim taxId As String = jsonInvoice("customer")("taxId").ToString()
Else
Dim taxId As String = "NOT_PROVIDED"
End If
' Alternatively, verify key presence via JObject.ContainsKey()
If jsonInvoice.ContainsKey("discountCode") Then
Dim discount As String = jsonInvoice("discountCode").ToString()
End If
In-Memory JSON Modification
Developers can modify, add, and remove properties in-place before forwarding payloads to downstream APIs:
' VB.NET: Updating and adding properties in JObject
jsonPayload("status") = "PROCESSED"
jsonPayload("processedTimestamp") = DateTime.UtcNow.ToString("o")
' Adding a new nested object
Dim auditObj As New JObject()
auditObj("robotId") = "BOT-04"
auditObj("executionMachine") = Environment.MachineName
jsonPayload("audit") = auditObj
' Removing a sensitive property
jsonPayload.Remove("creditCardCVV")
3. Declarative JSONPath Querying with .SelectToken() and .SelectTokens()
Chained indexer navigation (json("a")("b")(0)("c")) is brittle when JSON structures are deeply nested or when schemas contain optional hierarchy levels. JSONPath is the declarative query language for JSON (analogous to XPath for XML).
Newtonsoft.Json provides native JSONPath evaluation via .SelectToken() and .SelectTokens().
JSONPath Syntax Fundamentals
| Syntax Token | Meaning | Architectural Description |
|---|---|---|
$ | Root object | Refers to the root JSON element of the query. |
. | Child operator | Navigates to a direct child property (e.g., $.store.book). |
.. | Recursive descent | Searches for matching keys across all descendant levels regardless of depth. |
* | Wildcard | Matches all element properties or all array items. |
[n] | Array index | Selects the element at zero-based array index n. |
[?(@.expr)] | Filter expression | Filters array elements based on a logical predicate. |
Querying with .SelectToken()
.SelectToken(path): Returns a singleJTokenmatching the path. If no matching token is found, it returnsNothing(null) without throwing an exception, enabling safe null-conditional evaluation!.SelectTokens(path): Returns anIEnumerable(Of JToken)containing all matching elements across the structure.
' VB.NET: Deep extraction using JSONPath
Dim sampleJson As String = "{ 'store': { 'books': [ { 'title': 'RPA Pro', 'price': 49.99, 'category': 'Tech' }, { 'title': 'Automation Arch', 'price': 59.99, 'category': 'Tech' }, { 'title': 'History', 'price': 19.99, 'category': 'General' } ] } }"
Dim storeObj As JObject = JObject.Parse(sampleJson)
' Extract the title of the first book directly
Dim firstTitle As String = storeObj.SelectToken("$.store.books[0].title").ToString()
' Extract all tech books using a filter expression
Dim techBooks As IEnumerable(Of JToken) = storeObj.SelectTokens("$.store.books[?(@.category == 'Tech')]")
For Each book As JToken In techBooks
Console.WriteLine("Tech Book: " & book("title").ToString() & " | Price: $" & book("price").ToString())
Next
' Safe extraction: non-existent path returns Nothing without throwing
Dim discountToken As JToken = storeObj.SelectToken("$.store.discounts.holiday")
If discountToken IsNot Nothing Then
' Process discount
End If
4. Object Serialization & Strongly Typed Deserialization (JsonConvert)
While dynamic manipulation with JObject is flexible, enterprise workflows requiring strict data contracts, compile-time validation, and automated schema enforcement benefit from strongly typed serialization and deserialization via Newtonsoft.Json.JsonConvert.
Serializing In-Memory Objects to JSON
The JsonConvert.SerializeObject() method converts .NET data structures—including DataTable, Dictionary(Of String, Object), arrays, and custom classes—into standardized JSON strings:
' VB.NET: Serializing a Dictionary to JSON
Dim requestData As New Dictionary(Of String, Object) From {
{"TransactionID", "TX-9901"},
{"Amount", 1250.75},
{"IsApproved", True},
{"ProcessedAt", DateTime.UtcNow}
}
Dim jsonPayload As String = JsonConvert.SerializeObject(requestData, Newtonsoft.Json.Formatting.Indented)
' VB.NET: Serializing an entire DataTable to JSON table format
Dim jsonTable As String = JsonConvert.SerializeObject(dt_TransactionResults, Newtonsoft.Json.Formatting.None)
Deserializing to Strongly Typed Classes (POCO / DTO)
Defining Plain Old CLR Objects (POCO) or Data Transfer Objects (DTO) provides compile-time property safety, IntelliSense in Studio, and automatic type conversion:
' Class definition: put it in a code source file in the project or in a referenced library
' (Invoke Code bodies cannot declare classes)
Public Class InvoiceDto
Public Property InvoiceNumber As String
Public Property VendorCode As String
Public Property TotalAmount As Decimal
Public Property DueDate As DateTime
End Class
' VB.NET: Strongly typed deserialization
Dim invoiceData As InvoiceDto = JsonConvert.DeserializeObject(Of InvoiceDto)(rawJsonString)
' Direct strongly-typed property access with zero casting:
Dim invNum As String = invoiceData.InvoiceNumber
Dim total As Decimal = invoiceData.TotalAmount
// C#: Strongly typed deserialization
InvoiceDto invoiceData = JsonConvert.DeserializeObject<InvoiceDto>(rawJsonString);
string invNum = invoiceData.InvoiceNumber;
decimal total = invoiceData.TotalAmount;
Architectural Comparison: Dynamic JObject vs. Strongly Typed DTO
| Criterion | Dynamic JObject (UiPath.WebAPI) | Strongly Typed POCO/DTO (JsonConvert) |
|---|---|---|
| Setup Overhead | Zero setup; parse immediately from string | Requires defining a class or data model |
| Schema Flexibility | High; adapts dynamically to payload variations | Rigid; schema mismatches may fail or ignore fields |
| Type Safety | None; requires runtime casting (.ToString(), Convert) | Full compile-time type safety and IntelliSense |
| Maintenance Burden | Prone to runtime typos in string property names | High maintainability; refactoring tools update properties |
| Best Used For | Dynamic API responses, unknown schemas, small payloads | Core enterprise domain models, REFramework transaction data |
JSON in Everyday UiPath Work
JSON shows up in several places on the exam:
- HTTP Request activities and Integration Service connectors return JSON bodies that you deserialize before reading fields.
- Orchestrator HTTP Request returns Orchestrator API responses as JSON strings, for example a list of queue items under a
valuearray. - Webhook payloads from Orchestrator are JSON documents with properties such as
Type,EventId, andTimestamp. - Queue item SpecificContent is stored as JSON in Orchestrator. Its size is limited to 256,000 characters (512,000 bytes), so large documents belong in a storage bucket with only a link in the item.
A developer receives a complex JSON payload containing a deeply nested array of supplier records. The developer must retrieve the postal code of the first supplier without triggering a NullReferenceException if any parent container is missing. Which approach best achieves this?
Chaining visual Get XML Node activities after converting the JSON to XML
Using nested indexers: jsonResponse("suppliers")(0)("contact")("address")("postalCode").ToString() wrapped in an unhandled Assign
Using the JSONPath method: jsonResponse.SelectToken("$.suppliers[0].contact.address.postalCode") and checking if the resulting token IsNot Nothing
Looping through jsonResponse.Children() using a For Each activity and evaluating string Contains on every line
A workflow has a JObject named order. Which expression returns the value of order.customer.name without throwing when the customer property is missing?
order("customer")("name").ToString()
order.SelectToken("customer.name"), then check the result for Nothing before reading it
order.Item(0).Item(1).ToString()
JsonConvert.SerializeObject(order).Contains("name")
An API returns a JSON array of invoices at the top level (the body starts with "["). Which activity output type should the developer use to parse it?
Deserialize JSON with the default JObject type argument.
Deserialize XML followed by Get XML Nodes.
Read CSV with a comma delimiter.
Deserialize JSON Array, which outputs a JArray that can be iterated with For Each.
Sections you finish are checked off in the contents.