Swift 4 - How to convert Json to Swift Object automatically like Gson in java
I am new to Swift 4 and am trying to figure out how to automatically convert Json to swift Object like Gson in Java. Is there any plugin I can use that can convert my JSON to object and vice versa. I tried to use SwiftyJson library but couldn't figure out what is the syntax to convert json to Mapper object directly. In Gson, the conversion looks like this:
String jsonInString = gson.toJson(obj);
Staff staff = gson.fromJson(jsonInString, Staff.class);
Can you provide a really simple example for beginners like me. below is my swift man class:
class Person {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
below is the method call to get the response from the server:
let response = Helper.makeHttpCall(url: "http://localhost:8080/HttpServices/GetBasicJson", method: "PUT", param: interestingNumbers)
In the response variable, I am getting JSON:
{
"firstName": "John",
"lastName": "doe"
}
There is no longer any need for external libraries in Swift. As of Swift 4, there are 2 protocols that can achieve what you are looking for: Decodable and Encodable , which are grouped into Codable typealias, and JSONDecoder .
You just need to create an object that matches Codable
( Decodable
should suffice in this example).
struct Person: Codable {
let firstName, lastName: String
}
// Assuming makeHttpCall has a callback:
Helper.makeHttpCall(url: "http://localhost:8080/HttpServices/GetBasicJson", method: "PUT", param: interestingNumbers, callback: { response in
// response is a String ? Data ?
// Assuming it Data
let person = try! decoder.decode(Person.self, for: response)
// Uncomment if it a String and comment the line before
// let jsonData = response.data(encoding: .utf8)!
// let person = try! decoder.decode(Person.self, for: jsonData)
print(person)
})
Additional Information:
source to share