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

Viewed 9997

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"
}
2 Answers

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"
        }

}
Related