Working with JSON
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 10 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Working with JSON in Microsoft Dynamics 365 Business Central
Introduction: The Universal Language of Data Integration
In the modern landscape of enterprise resource planning, no system exists in a vacuum. Whether you are connecting Microsoft Dynamics 365 Business Central to a third-party shipping provider, a web storefront, or an internal analytics dashboard, you are almost certainly going to encounter JSON. Standing for JavaScript Object Notation, JSON has become the de facto standard for data interchange on the web. It is lightweight, human-readable, and supported by virtually every programming language in existence.
For a Business Central developer or consultant, mastering the art of handling JSON is not just a useful skill; it is a fundamental requirement for building integrations. When you interact with a REST API, you receive data in JSON format and send data by constructing JSON objects. If you do not understand how to parse, manipulate, and generate this data structure correctly, your integration efforts will be fragile, prone to errors, and difficult to maintain.
This lesson explores the mechanics of working with JSON within the Business Central environment using AL (Application Language). We will move beyond the basics, looking at how to navigate complex nested objects, handle arrays, and ensure that your code remains performant even when dealing with large payloads. By the end of this module, you will have the confidence to build robust integrations that communicate effectively with any external service.
Not read yet
Understanding the JSON Structure
Before we write code, we must understand what we are dealing with. JSON is a text-based format that represents data as a collection of name-value pairs. It is derived from JavaScript, but it is entirely independent of it. There are two primary structures in JSON: objects and arrays.
An object is an unordered set of name-value pairs, enclosed in curly braces {}. Each name is a string, followed by a colon, and then the value. An array is an ordered collection of values, enclosed in square brackets []. These values can be strings, numbers, objects, arrays, booleans, or null.
Key Data Types in JSON
- Strings: Must be enclosed in double quotes.
- Numbers: Integers or floating-point numbers.
- Booleans: Either
trueorfalse. - Null: Represents an empty value.
- Objects: Nested structures using
{}. - Arrays: Ordered lists using
[].
Callout: JSON vs. XML While XML was the dominant format for data interchange for many years, JSON has largely superseded it in web APIs. XML is verbose and requires a complex schema (XSD) to define its structure, which often leads to heavy parsing overhead. JSON is much more concise, maps directly to data structures in modern programming languages, and is significantly faster to process for machines. For Business Central integrations, you will encounter XML only when working with legacy SOAP services; for everything else, assume JSON.
Not read yet
Navigating the AL JSON Library
Business Central provides a set of built-in data types in AL specifically designed to handle JSON. You do not need to rely on external libraries or complex string manipulation. Instead, you will work with the JsonObject, JsonArray, JsonToken, and JsonValue data types.
The Core Data Types
- JsonObject: Represents a collection of key-value pairs. You use this to build or read the root of a JSON document.
- JsonArray: Represents an ordered list of items. This is essential when an API returns a list of records, such as a list of customers or sales orders.
- JsonToken: This is the base type. Every JSON element is technically a token. You use this when you are not sure if the incoming data will be an object, an array, or a simple value.
- JsonValue: Represents a primitive value within a JSON structure, such as a string, integer, or boolean.
Practical Example: Parsing an Incoming JSON Payload
Imagine a scenario where an external logistics provider sends a confirmation of a shipment back to your Business Central environment. The payload looks like this:
{
"shipmentId": "SHIP-1001",
"status": "Delivered",
"items": [
{"itemId": "Item-A", "quantity": 5},
{"itemId": "Item-B", "quantity": 2}
]
}
To process this in AL, you first need to parse the string into a JsonObject.
Step-by-Step Parsing Logic
- Read the string into a JsonToken: Use the
ReadFrommethod. - Convert to JsonObject: Once read, you can cast the token to an object to access its keys.
- Extract Values: Use the
SelectTokenorGetmethods to pull data out. - Iterate Arrays: If you encounter an array, use a
foreachloop to process each item.
procedure ProcessShipment(JsonResponse: Text)
var
JToken: JsonToken;
JObject: JsonObject;
JArray: JsonArray;
JItemToken: JsonToken;
JItemObject: JsonObject;
ShipmentId: Text;
begin
// 1. Parse the text into a JsonToken
if not JToken.ReadFrom(JsonResponse) then
Error('Invalid JSON format');
// 2. Convert to JsonObject
JObject := JToken.AsObject();
// 3. Extract a simple value
if JObject.Get('shipmentId', JToken) then
ShipmentId := JToken.AsValue().AsText();
// 4. Access an array
if JObject.Get('items', JToken) then begin
JArray := JToken.AsArray();
foreach JItemToken in JArray do begin
JItemObject := JItemToken.AsObject();
// Process individual items here
end;
end;
end;
Note: Always check if a key exists using the
.Get()method before trying to access it. If you try to access a key that does not exist, your code might throw an error or behave unexpectedly. The.Get()method returns a boolean, making it perfect for safe conditional checks.
Not read yet
Constructing JSON for Outbound Requests
Often, you are the one sending data to an external service. You must build a JsonObject that matches the expected schema of the target API.
Building a Nested Object
When creating JSON, you start with an empty object and add properties. You can add primitives, but you can also add other objects or arrays as values.
procedure CreateSalesOrderJson(): Text
var
JObject: JsonObject;
JArray: JsonArray;
JItem: JsonObject;
JsonText: Text;
begin
// Create the root object
JObject.Add('orderNumber', 'SO-5001');
JObject.Add('customer', 'CUST-001');
// Create an array for items
JItem.Add('itemId', 'ITEM-100');
JItem.Add('qty', 10);
JArray.Add(JItem);
// Add the array to the root object
JObject.Add('lineItems', JArray);
// Convert to text to send via HTTP
JObject.WriteTo(JsonText);
exit(JsonText);
end;
Best Practices for Construction
- Use Descriptive Keys: Ensure the keys match exactly what the API documentation specifies. JSON is case-sensitive, so
orderNumberis different fromordernumber. - Validate Types: Ensure that if an API expects a number, you are providing a numeric value and not a string. While some APIs are forgiving, many strict REST services will reject the request if the types do not match the documentation.
- Clean Up: If you are reusing objects within a loop, remember to clear or re-initialize them to prevent data from previous iterations from leaking into new ones.
Not read yet
Handling Complex Data Structures and Deep Nesting
In real-world scenarios, APIs rarely provide flat structures. You will often deal with deeply nested hierarchies. Navigating these requires a clear understanding of the SelectToken method, which supports JSON Path expressions.
JSON Path is a syntax that allows you to point to specific parts of a JSON document using a string expression. For example, if you want to reach the third item in an array nested inside an object, you could use $.store.book[2].title.
Using SelectToken for Deep Access
Instead of manually navigating through five levels of Get calls, you can use SelectToken to jump directly to the data you need.
procedure GetNestedValue(JObject: JsonObject)
var
JToken: JsonToken;
begin
// Accessing a deeply nested property using JSON Path
if JObject.SelectToken('data.customer.address.city', JToken) then
Message('The city is: %1', JToken.AsValue().AsText());
end;
This approach significantly reduces the amount of boilerplate code required to drill down into complex objects. It makes your code cleaner and easier to read, especially when the JSON structure is provided by a third-party vendor who might change the nesting depth in future updates.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced developers fall into common traps when working with JSON in Business Central. Here are the most frequent issues and how to steer clear of them.
1. The "Case-Sensitivity" Trap
JSON keys are case-sensitive. If an API documentation states that the field is customerID, requesting customerid will return a null or cause an error. Always double-check your casing against the API specification.
2. Ignoring Null Values
Some APIs return null for fields that have no value, while others omit the key entirely. If your code assumes a key will always be present, you will trigger a runtime error when it is missing. Always use JObject.Contains('key') or the boolean return of JObject.Get() to verify the presence of a key before accessing it.
3. Mixing Types in Arrays
While JSON allows for mixed-type arrays (e.g., ["text", 123, true]), most REST APIs are strictly typed. If an array is defined as a list of objects, sending an array containing a mix of strings and objects will cause a 400 Bad Request error. Ensure your data structure is consistent.
4. Memory Management with Large Payloads
If you are processing massive JSON files—such as a catalog with 50,000 items—loading the entire structure into memory as a JsonObject can lead to performance degradation or even memory limit errors. In such cases, consider if you can process the data in chunks or use a streaming approach if the API supports it.
Warning: Be cautious when using
JsonToken.AsObject()orJsonToken.AsArray()without validating the type first. If you attempt to treat a primitiveJsonValueas an object, your code will throw a runtime error. Always use the.IsObject()or.IsArray()methods to perform a type check before casting.
Not read yet
Comparison: Accessing JSON Data
| Method | Best Use Case | Pros | Cons |
|---|---|---|---|
JObject.Get() |
Simple, flat objects | Fast, easy to read | Requires multiple calls for deep nesting |
JObject.SelectToken() |
Complex, nested objects | Concise, powerful syntax | Slightly more overhead than Get() |
foreach loop |
Iterating over arrays | Clean and idiomatic | Can be slow with very large arrays |
Advanced Techniques: Working with Dates and Decimals
JSON does not have a native date type. Dates are typically passed as ISO 8601 strings (e.g., 2023-10-27T10:00:00Z). When receiving these, you must manually parse the string into a Business Central Date or DateTime variable.
procedure ParseDate(DateString: Text): DateTime
var
ResultDate: DateTime;
begin
if Evaluate(ResultDate, DateString, 9) then // 9 is the ISO format
exit(ResultDate);
end;
Similarly, decimals can sometimes be represented as strings in JSON to avoid precision issues in certain systems. Always use Evaluate or the built-in type conversion methods to ensure that your Business Central variables match the incoming data types accurately.
Not read yet
Industry Standards and Best Practices
When integrating Business Central with external systems, your code should be maintainable and resilient. Follow these industry-standard practices:
- Implement Error Handling: Wrap your JSON parsing logic in
try-catchblocks where appropriate. If an API call returns an unexpected format, your system should log the error and notify an administrator rather than crashing the entire integration process. - Validate Before Processing: If you are receiving data from an external source, treat it as "untrusted." Validate the structure and the content before attempting to insert or update data in your Business Central tables.
- Use Constants for Keys: Instead of hardcoding strings like
'customerNumber'throughout your code, define them as constants at the start of your codeunit. This makes it easier to update the integration if the API schema changes later. - Document the Mapping: Maintain a document that maps your Business Central fields to the corresponding JSON keys. This is invaluable when troubleshooting issues or onboarding new developers to the project.
- Log the Raw Request/Response: During development and troubleshooting, log the raw JSON payload. This allows you to see exactly what was sent or received, which is often the only way to debug issues with third-party APIs.
Not read yet
Frequently Asked Questions (FAQ)
Q: Can I use JSON for large data imports into Business Central? A: Yes, but keep in mind that Business Central has limits on request sizes and processing times. For very large datasets, consider using the Data Exchange Framework or batching your requests into smaller chunks to avoid timeout errors.
Q: Is there a built-in way to validate JSON against a schema? A: Business Central does not have a built-in JSON Schema validator. You must implement your own validation logic, such as checking for the presence of required keys and verifying that values fall within expected ranges.
Q: Why does my JSON look different when I write it to a file?
A: JsonObject.WriteTo() produces a compact string by default. If you need it to be "pretty-printed" for human readability, you may need to use a custom formatter, though this is rarely necessary for machine-to-machine communication.
Q: How do I handle special characters in JSON strings?
A: The AL JSON library automatically handles escaping for special characters (like quotes, backslashes, and newlines) when you add them to a JsonObject. You do not need to manually escape these characters yourself.
Not read yet
Summary of Key Takeaways
- JSON is Essential: It is the primary language of modern web integration. Proficiency in the
JsonObject,JsonArray, andJsonTokentypes is mandatory for any Business Central developer. - Type Safety Matters: Always verify the type of a token (e.g., using
.IsObject()or.IsArray()) before casting it to a specific type to prevent runtime errors. - Use
SelectTokenfor Complexity: When dealing with deep, nested structures, leverage JSON Path expressions withSelectTokento keep your code clean and manageable. - Prioritize Defensive Coding: Never assume an API will return exactly what you expect. Always check for the existence of keys and handle null values gracefully to build resilient integrations.
- Standardize Your Approach: Use constants for JSON keys and maintain clear mapping documentation to ensure that your integrations are easy to maintain and update over time.
- Performance Matters: When dealing with large payloads, be mindful of memory usage and consider batching your data to ensure that your integration remains responsive.
- Log for Debugging: Always implement logging for the raw JSON payloads during development. Having visibility into exactly what is being transmitted is the fastest way to resolve integration issues.
By following these principles, you will be well-equipped to handle any JSON-based integration requirement that comes your way. Whether you are building a simple connection to a weather service or a complex synchronization bridge between Business Central and a global e-commerce platform, the techniques covered here will serve as the foundation of your success. Remember that integration is an iterative process; start small, validate your data, and build your logic layer by layer.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820