如何在swift中解析这个json?

我有一个请求

Alamofire.request(.GET,HttpHelper.baseURL+HttpHelper.tripsURL,encoding:.JSON).responseJSON { response in var json = JSON(data: response.data!) print(json) print(json["res"]) } 

然后是结果

 { "res" : "[{\"name\":\"testName\",\"lastName\":\"testLastName\"},{\"name\":\"testName\",\"lastName\":\"testLastName\"}]", "status" : "success", "out" : "{\"name\":\"testName\",\"lastName\":\"testLastName\"}" } [{"name":"testName","lastName":"testLastName"},{"name":"testName","lastName":"testLastName"}] 

我如何设置数据从res到struct或类User

 struct User { var name : String? var lastName : String? } 

请帮忙解决这个问题)非常感谢!!)

你可以做那样的事情

 var result: [User]() for user in json["res"] { let userTmp = User(name: user["name"], lastName: user["lastName"]) result.append(userTmp) } 

问候

基本上,它将是:

 class User { var name : String? var lastName : String? } var theUsers = [User]() Alamofire.request(.GET,HttpHelper.baseURL+HttpHelper.tripsURL,encoding:.JSON) .responseJSON { response in var json = JSON(data: response.data!) print(json) theUsers = json["res"].map { return User (name: $0["name"], lastName: $0.["lastName"]) } }) 

但是,在此过程中,您可能需要进行一些类型转换。 例如,可以将( json["res"]替换为(json["res"] as Array>) ,以保持类型检查器和类型推理器的快乐。

我正在使用本机Codable协议来做到这一点:

 class MyClass: Codable { var int: Int? var string: String? var bool: Bool? var double: Double? } let myClass = MyClass() myClass.int = 1 myClass.string = "Rodrigo" myClass.bool = true myClass.double = 2.2 if let json = JsonUtil.toJson(myClass) { print(json) // {"bool":true,"string":"Rodrigo","double":2.2,"int":1} if let myClass = JsonUtil.from(json: json) { print(myClass.int ?? 0) // 1 print(myClass.string ?? "nil") // Rodrigo print(myClass.bool ?? false) // true print(myClass.double ?? 0) // 2.2 } } 

我创建了一个JsonUtil来帮助我:

 public struct JsonUtil { public static func from(json: String) -> T? { if let jsonData = json.data(using: .utf8) { let jsonDecoder = JSONDecoder() do { return try jsonDecoder.decode(T.self, from: jsonData) } catch { print(error) } } return nil } public static func toJson(_ obj: T) -> String? { let jsonEncoder = JSONEncoder() do { let jsonData = try jsonEncoder.encode(obj) return String(data: jsonData, encoding: String.Encoding.utf8) } catch { print(error) return nil } } } 

如果你的对象中有任何类型的问题。 请看我的另一个答案:

https://stackoverflow.com/a/51728972/3368791

祝你好运 :)

Interesting Posts