Swift 4 - How to convert Json to swift Object automatically like Gson in java Swift 4 - How to convert Json to swift Object automatically like Gson in java json json

Swift 4 - How to convert Json to swift Object automatically like Gson in java


There's no need for external libraries in Swift anymore. As of Swift 4, there are 2 protocols that can achieve what you are looking for: Decodable and Encodable which are grouped into the Codable typealias, as well as JSONDecoder.

You just need to create an entity that conforms to Codable (Decodable should be enough 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's Data    let person = try! decoder.decode(Person.self, for: response)    // Uncomment if it's a String and comment the line before    // let jsonData = response.data(encoding: .utf8)!    // let person = try! decoder.decode(Person.self, for: jsonData)    print(person)})

More info:


As @nathan Suggested

"There's no need for external libraries in Swift anymore."

But If you still want to go with the third party library like ObjectMapper

class Person : Mappable {    var firstName: String?    var lastName: String?    required init?(map:Map) {    }   func mapping(map:Map){      //assuming the first_name and last_name is what you have got in JSON      // e.g in android you do like @SerializedName("first_name") to map     firstName <- map["first_name"]     lastName <- map["last_name"]   }}let person = Mapper<Person>().map(JSONObject:response.result.value)

and extending the answer by @nathan to demonstrate @SerializedName annotation equivalent in iOS using Codable

struct Person : Codable {        let firstName : String?        let lastName : String?        enum CodingKeys: String, CodingKey {                case firstName = "first_name"                case lastName = "last_name"        }}