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

user6457240 picture user6457240 · Jul 19, 2017 · Viewed 8k times · Source

I am new in Swift 4 and trying to figure out How to convert Json to swift Object automatically like Gson in java. Is there is any plugin i can use which can convert my json to object and vice versa. I have tried to use SwiftyJson Library but couldnt understand what is syntax for directly converting the json to object mapper. In Gson conversion is as follow :

String jsonInString = gson.toJson(obj);
Staff staff = gson.fromJson(jsonInString, Staff.class);

Can you please suggest some really simple example for beginner like me . below is my swift person class :

class Person  {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

below is method call to fetch response from server :

let response = Helper.makeHttpCall(url: "http://localhost:8080/HttpServices/GetBasicJson", method: "PUT", param: interestingNumbers)

In response variable I am getting json:

{
  "firstName": "John",
  "lastName": "doe"
}

Answer

nathan picture nathan · Jul 21, 2017

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: