gpt4 book ai didi

ios - Swift:如何使用 Alamofilre 或 SwiftyJSON 将 JSON 字符串转换为 ObjectMapper?

转载 作者:搜寻专家 更新时间:2023-10-31 22:22:36 26 4
gpt4 key购买 nike

我目前正在使用 ObjectMapper用于将 JSON 对象从 API 映射到模型对象的 Swift

但是我的 restful api 返回 API 看起来像这样:

{
success: true,
data:
[{
"stats":{
"numberOfYes":0,
"numberOfNo":2,
"progress":{
"done":false,
"absolute":"2/100",
"percent":2
}
},
"quickStats":null,
"uid":5,
"name":"Flora",
"imageArray":[
"http://s3.com/impr_5329beac79400000",
"http://s3.com/impr_5329beac79400001"
],
"metaData":{
"description":"Floral Midi Dress",
"price":"40$"
}
}]

}

在数据节点中是数组,我无法使用此代码查找映射

let json = JSON(responseObject!)

for tests in json["impressions"][0] {
let test = Mapper<myTests>().map(tests)
println(test?.impressionID)
}

我该如何解决?谢谢

** 已编辑 **我找到了类似@tristan_him 的解决方案

ObjectModel映射结构

class Response: Mappable {
var success: Bool?
var data: [Data]?

required init?(_ map: Map) {
mapping(map)
}

func mapping(map: Map) {
success <- map["success"]
data <- map["data"]
}
}

class Data: Mappable {
var uid: Int?
var name: String?
// add other field which you want to map

required init?(_ map: Map) {
mapping(map)
}

func mapping(map: Map) {
uid <- map["uid"]
name <- map["name"]
}
}

使用 Alamofire 响应映射

let response: Response = Mapper<Response>().map(responseObject)!

for item in response.data! {
let dataModel: Data = item
println(dataModel.name)
}

最佳答案

您可以使用以下类结构映射上面的 JSON:

class Response: Mappable {
var success: Bool?
var data: [Data]?

required init?(_ map: Map) {
mapping(map)
}

func mapping(map: Map) {
success <- map["success"]
data <- map["data"]
}
}

class Data: Mappable {
var uid: Int?
var name: String?
// add other field which you want to map

required init?(_ map: Map) {
mapping(map)
}

func mapping(map: Map) {
uid <- map["uid"]
name <- map["name"]
}
}

然后你可以映射如下:

let response = Mapper<Response>().map(responseObject)
if let id = response?.data?[0].uid {
println(id)
}

关于ios - Swift:如何使用 Alamofilre 或 SwiftyJSON 将 JSON 字符串转换为 ObjectMapper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com