Keywords: JSON | Swift 4 | Parsing | JSONSerialization | Codable
Abstract: This article explores the conversion of JSON strings to objects in Swift 4, highlighting common errors such as mistaking arrays for dictionaries. It demonstrates both traditional JSONSerialization and modern Codable approaches with reorganized code examples and best practices to help developers avoid pitfalls.
Introduction
In Swift 4 development, converting JSON strings to objects is a common task, but it can lead to errors if not handled properly. A frequent mistake is assuming that a JSON string represents a dictionary when it might be an array, resulting in nil during JSONSerialization.
Using JSONSerialization to Parse JSON Arrays
Based on the best answer, the issue arises from incorrectly casting the JSON object as a dictionary. The JSON string begins with [, indicating an array. Here is an improved version of the solution:
let jsonString = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = jsonString.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [Dictionary<String, Any>] {
print(jsonArray)
} else {
print("Invalid JSON")
}
} catch {
print(error)
}
This code uses the .allowFragments option to handle JSON fragments. Note that in the output, null values are represented as <null>, which is normal.
Using Codable for Type-Safe Decoding
As a supplementary reference, Swift 4 introduced Codable, which offers a more elegant way. Define a struct conforming to Codable and use JSONDecoder:
struct Form: Codable {
let id: Int
let name: String
let description: String?
private enum CodingKeys: String, CodingKey {
case id = "form_id"
case name = "form_name"
case description = "form_desc"
}
}
let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
if let data = data.data(using: .utf8) {
do {
let forms = try JSONDecoder().decode([Form].self, from: data)
print(forms)
} catch {
print(error)
}
}
This method provides compile-time safety and better error handling.
Conclusion
When working with JSON in Swift 4, it is crucial to identify the JSON structure first. For quick parsing, JSONSerialization is suitable, but for complex scenarios, Codable is recommended. Always test with sample data to avoid common pitfalls.