An open API service indexing awesome lists of open source software.

https://github.com/esraasem2/delphi-rest-json-optional

Delphi REST JSON Optional showcases JSON serialization with optional fields in Delphi. Explore clean API architecture and reusable HTTP services. πŸ™βœ¨
https://github.com/esraasem2/delphi-rest-json-optional

api-integration clean-architecture delphi example-project json object-pascal optional-fields rest-api serialization vcl

Last synced: about 1 year ago
JSON representation

Delphi REST JSON Optional showcases JSON serialization with optional fields in Delphi. Explore clean API architecture and reusable HTTP services. πŸ™βœ¨

Awesome Lists containing this project

README

          

# πŸš€ Delphi REST JSON Optional

> πŸ‡§πŸ‡· [Leia este README em portuguΓͺs](./README.md)

> Example project in Delphi demonstrating JSON serialization with optional fields and clean API architecture.

[![Delphi](https://img.shields.io/badge/Delphi-11.3-red.svg)](https://www.embarcadero.com/products/delphi)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](#)

---

## πŸ“Œ About the Project

This is a demo project using Delphi (VCL) that demonstrates how to:

- Use generic optional types (`TOptional`) with serialization support
- Generate JSON including or omitting `null` fields
- Separate payload (request) and response models
- Use RTTI with `published` properties for serialization
- Integrate with a clean and reusable HTTP service layer

---

## πŸ—‚ Structure

```
DelphiRestJsonOptional/
β”œβ”€β”€ API.Abstract.Service.pas # Base HTTP service
β”œβ”€β”€ API.Lancamento.Service.pas # Example for posting data
β”œβ”€β”€ API.Types.Optional.pas # Generic type definition: TOptional
β”œβ”€β”€ DelphiRestJsonOptional.dpr # Main Delphi VCL project
β”œβ”€β”€ README.md # This file (Portuguese)
β”œβ”€β”€ README.en.md # English version
```

---

## βœ… How to use `TOptional`
---

## πŸ”„ Implicit and Explicit Conversion with TOptional

The `TOptional` class supports automatic (implicit) conversions to simplify usage:

### βœ… From native value to TOptional

```delphi
Payload.ContaBancariaId := 123;
// Equivalent to:
Payload.ContaBancariaId := TOptional.Create(123);
```

### βœ… From TOptional to native value

```delphi
var
id: Integer;
begin
if Payload.ContaBancariaId.HasValue then
id := Payload.ContaBancariaId;
// Equivalent to:
id := Payload.ContaBancariaId.GetValue;
```

### ⚠️ Important

If `HasValue = False`, converting to the native type will raise an exception.
Always check `HasValue` before accessing the value directly.

This project uses the generic type `TOptional` to clearly and reliably handle optional fields.

### πŸ“Œ Examples:

```delphi
// Integer with value (will be serialized as a number)
Payload.ContaBancariaId := TOptional.Create(123);

// Integer with no value (will be serialized as null)
Payload.ContaBancariaId := TOptional.Create(0); // Interpreted as null
// or explicitly:
Payload.ContaBancariaId := TOptional.Empty;

// String with value
Payload.NumeroDocumento := TOptional.Create('ABC123');

// Empty string (will be serialized as null)
Payload.NumeroDocumento := TOptional.Create('');
```

The type `TOptional` automatically interprets the content:
- For numeric types: `0` is treated as no value
- For strings: `''` (empty string) is treated as no value
- You can use `TOptional.Empty` to explicitly mark a value as `null`

---

## βœ… Features

1. The **"Generate JSON"** button creates an object with preset values
2. Serializes it using RTTI + `TOptional` handling
3. The **"Load JSON"** button simulates API response reading
4. Deserializes the JSON and fills the response object

---

## πŸ›  Requirements

- Delphi **11.3** or higher
- VCL Forms Application project

---

## πŸ§ͺ How to run

1. Open the project `DelphiRestJsonOptional.dpr` in Delphi
2. Compile and run
3. Click **"Generate JSON"** to see the request payload
4. Optionally edit the JSON and click **"Load JSON"**

---

## πŸ’‘ Why use this?

Many modern APIs differentiate between `0`, `''` and `null` values β€” and handling this properly in Delphi is often challenging.

This project provides a lightweight solution fully compatible with **Delphi Professional** (no `JSONInterceptor` needed), using RTTI and a generic optional wrapper type `TOptional`.

---

## πŸ“€ Example JSON Output

```json
{
"parceiro_id": 123,
"empresa_filial_unidade_id": 0,
"classificacao_id": 0,
"numero_documento": "ABC123",
"data_vencimento": "2025-01-15",
"data_competencia": "2025-01-01",
"valor": 250.5,
"pago": false,
"conta_bancaria_id": null,
"data_pagamento": null
}
```

---

## 🀝 Contributions

Suggestions, feedback, and contributions are welcome!
Feel free to open an issue or submit a pull request.

---

## πŸ‘€ Author

Created by [Ivonei Balena](mailto:iibalena@gmail.com)
[LinkedIn](https://www.linkedin.com/in/ivonei-balena-a9a26465/)

---

## πŸ“„ License

This project is licensed under the terms of the [MIT License](LICENSE).