In this short tutorial, you will learn how to convert JSON string to a struct or a class in Swift.
JSON String
Let’s assume we have a web service endpoint which returns us a JSON string containing the following user details:
{"firstName":"Sergey","lastName":"Kargopolov","email":"[email protected]","userId":"7fc0631b-7116-4d41-8d87-78f97b4dc543"}
Swift Data Structure. Conforming to Codable or Encodable.
We need to write Swift code to convert the above JSON string to a Swift struct or a class. Below is a code snippet of Swift struct into which we want to convert our JSON string.
struct UserResponseModel: Decodable { let firstName: String let lastName: String let email: String let userId: String }
There are two very important details to note:
- Your Swift class or a struct must have properties which names match the keys in a JSON string. For example, the struct field name firstName must match the name of the in the JSON string firstName. If field names do not match, you will get an error message: “The data couldn’t be read because it is missing..”
- Swift class or struct must conform to a Decodable or Codable protocol. In the code snippet above the UserResponseModel struct conforms to a Decodable protocol.
Convert JSON String to Data
Before we can convert JSON string to a Swift data structure we need to first convert JSON string to a Data object. You can do that with the following code snippet:
let jsonString = """ {"firstName":"Sergey","lastName":"Kargopolov","email":"[email protected]","userId":"7fc0631b-7116-4d41-8d87-78f97b4dc543"} """ // Convert JSON String to Data let data = Data(jsonString.utf8)
Convert JSON to Swift Data Structure
Now when you have JSON string converted to a Data object with the above code snippet you can use the below function to convert Data object to a Swift data structure.
// Function to parse JSON func parseJSON(data: Data) -> UserResponseModel? { var returnValue: UserResponseModel? do { returnValue = try JSONDecoder().decode(UserResponseModel.self, from: data) } catch { print("Error took place: \(error.localizedDescription).") } return returnValue }
Complete Example in Xcode Playground
Here is a complete code example you can copy and run in Xcode playground.
import UIKit let jsonString = """ {"firstName":"Sergey","lastName":"Kargopolov","email":"[email protected]","userId":"7fc0631b-7116-4d41-8d87-78f97b4dc543"} """ struct UserResponseModel: Decodable { let firstName: String let lastName: String let email: String let userId: String } // Convert JSON String to Data let data = Data(jsonString.utf8) // Function to parse JSON func parseJSON(data: Data) -> UserResponseModel? { var returnValue: UserResponseModel? do { returnValue = try JSONDecoder().decode(UserResponseModel.self, from: data) } catch { print("Error took place: \(error.localizedDescription).") } return returnValue } if let userModel = parseJSON(data: data) { print(" userId = \(userModel.userId)") }
I hope this short tutorial on how to convert JSON string to a class or a struct in Swift was helpful to you.
Check out other short but very useful and practical Swift code examples by searching this blog using Swift as a search word or simply checking Swift category.