Swift
JSON
Array
Programming
Data Conversion

Convert array to JSON string in swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting an array to a JSON string in Swift is usually a two-step process: encode the array into Data, then turn that data into a UTF-8 String. The best API depends on what the array contains. Use JSONEncoder for Codable types and JSONSerialization for loosely typed arrays such as [Any].

Use JSONEncoder for Codable Arrays

If your array elements are Codable, JSONEncoder is the cleanest option.

swift
1import Foundation
2
3struct User: Codable {
4    let id: Int
5    let name: String
6}
7
8let users = [
9    User(id: 1, name: "Ana"),
10    User(id: 2, name: "Ben")
11]
12
13do {
14    let encoder = JSONEncoder()
15    let data = try encoder.encode(users)
16    let json = String(data: data, encoding: .utf8)
17    print(json ?? "Invalid UTF-8")
18} catch {
19    print("Encoding failed: \(error)")
20}

This is the standard approach for application models because it is type-safe and easy to maintain.

Pretty-Printed JSON

If you want readable JSON for logs or debugging, set the encoder's formatting options.

swift
1let encoder = JSONEncoder()
2encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
3let data = try encoder.encode(users)
4let json = String(data: data, encoding: .utf8)
5print(json ?? "Invalid UTF-8")

That makes the output easier for humans to inspect, although compact JSON is usually better for network traffic.

Use JSONSerialization for [Any]

If you have a loosely typed array such as strings, numbers, dictionaries, or nested arrays, JSONSerialization is appropriate.

swift
1import Foundation
2
3let array: [Any] = [
4    "apple",
5    42,
6    ["name": "Ana", "active": true]
7]
8
9do {
10    guard JSONSerialization.isValidJSONObject(array) else {
11        fatalError("Array is not a valid JSON object")
12    }
13
14    let data = try JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
15    let json = String(data: data, encoding: .utf8)
16    print(json ?? "Invalid UTF-8")
17} catch {
18    print("Serialization failed: \(error)")
19}

This is useful when you are working with dynamic JSON-like structures rather than strongly typed models.

Know What JSON Can Represent

Not every Swift value can be turned into JSON directly. JSON supports strings, numbers, booleans, arrays, objects, and null values. It does not directly support arbitrary custom Swift objects, dates without conversion, or binary data without encoding.

That is why Codable models often need custom date or data strategies when the payload contains those types.

swift
1struct Event: Codable {
2    let title: String
3    let createdAt: Date
4}
5
6let encoder = JSONEncoder()
7encoder.dateEncodingStrategy = .iso8601

If you skip this kind of configuration, encoding may succeed in a format you did not intend, or it may fail for more complex types.

Converting the Data to a String

The final conversion step usually uses UTF-8:

swift
let jsonString = String(data: data, encoding: .utf8)

This returns an optional because not all byte sequences are valid UTF-8. For JSON generated by the standard encoders, UTF-8 is the normal expectation.

In many cases you do not actually need the string at all. If the JSON is being sent in a network request, the Data value is usually the better form to pass to URLRequest.

Common Pitfalls

The most common mistake is trying to encode a non-Codable custom object with JSONEncoder. That encoder expects types that conform to Encodable.

Another issue is using JSONSerialization with values that are not valid JSON objects. Check isValidJSONObject when using dynamic arrays or dictionaries.

Developers also often convert to a string too early. If the next step is an HTTP request, keep the JSON as Data until the boundary where text is actually required.

Finally, do not forget formatting strategies for dates, keys, or pretty printing when the default output does not match your API contract.

Summary

  • Use JSONEncoder for arrays of Codable values.
  • Use JSONSerialization for dynamic arrays such as [Any].
  • Convert the resulting Data to a UTF-8 string only when you actually need text output.
  • Validate dynamic JSON objects before serializing them.
  • Configure formatting and encoding strategies when the payload contains dates or other non-trivial types.

Course illustration
Course illustration

All Rights Reserved.