Converting Dictionary to JSON in Swift: Step-by-Step Guide
Hi everyone! I'm new to Swift and trying to understand JSON. I need to send data to the server in JSON format, and I'm storing it as a dictionary `[String: Any]`. For example, I have this dictionary:
```swift
let userDict: [String: Any] = [
"name": "Ivan",
"age": 30,
"isActive": true,
"address": [
"city": "Moscow",
"zip": "101000"
]
]
```
I tried using `JSONSerialization`, but I keep getting errors. Here's my code:
```swift
let jsonData = try JSONSerialization.data(withJSONObject: userDict, options: .prettyPrinted)
```
Error: `"Invalid value around key 'age'."` — I don't understand why this is happening. I read the documentation, but it seems complicated. Please advise how to properly convert a dictionary to JSON? Do I need to somehow validate
No answers yet.
Log in to leave an answer
Blogs
How to Become a JavaScript Developer in 2025: A Complete Roadmap
Deploying PHP on Kubernetes: A Basic Guide for Beginners
Monitoring JavaScript Applications: Metrics and Alerts from A to Z
A Day in the Life of a Kotlin Developer: Code, Coffee, and Coroutines