我是Swift 4的新手,试图找出如何将Json自动转换为swift对象,就像java中的Gson一样。是否有任何我可以使用的插件可以将我的json转换为对象,反之亦然。我曾尝试使用SwiftyJson库,但无法理解直接将json转换为对象映射器的语法是什么。 在Gson转换如下:
String jsonInString = gson.toJson(obj);
Staff staff = gson.fromJson(jsonInString, Staff.class);
你能为我这样的初学者推荐一些非常简单的例子吗?下面是我的快速课程:
class Person {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
下面是从服务器获取响应的方法调用:
let response = Helper.makeHttpCall(url: "http://localhost:8080/HttpServices/GetBasicJson", method: "PUT", param: interestingNumbers)
在响应变量中我得到了json:
{
"firstName": "John",
"lastName": "doe"
}
答案 0 :(得分:15)
Swift中不再需要外部库。从Swift 4开始,有2个协议可以实现您的目标:Decodable和Encodable分为Codable类型,以及JSONDecoder。
您只需创建符合Codable
的实体(在此示例中Decodable
就足够了。)
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)
})
更多信息:
答案 1 :(得分:1)
如@nathan建议
“ Swift不再需要外部库。”
但是,如果您仍然想使用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)
并通过@nathan扩展答案,以使用@SerializedName
Codable
注释
struct Person : Codable {
let firstName : String?
let lastName : String?
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
}
}