SwiftyJson从JSON

这是我json.file的复杂结构得到JSON的价值:SwiftyJson从JSON

[ 

{

"date_range": "2016-11-01-2016-12-31",

"order_status_id": 3,

"jobs": [

{

"date": "2016-11-14",

"job": [

{

"id": 143608,

"pickup_worker_id": null,

"drop_off_worker_id": 57

}

]

}

]

}

{

"date_range": "2016-11-01-2016-12-31",

"order_status_id": 2,

"jobs": [

{

"date": "2016-11-16",

"job": [

{

"id": 143238,

"pickup_worker_id": null,

"drop_off_worker_id": 12

},

{

"id": 13218,

"pickup_worker_id": null,

"drop_off_worker_id": 42

}

]

},

{

"date": "2016-11-19",

"job": [

{

"id": 141238,

"pickup_worker_id": null,

"drop_off_worker_id": 12

}

]

}

]

}

]


这是我为swiftyjson代码:

Alamofire.request(Constants.web_api+api_get_orders, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Constants.headers).responseJSON { (responseData) -> Void in 

if((responseData.result.value) != nil) {

let swiftyJsonVar = JSON(responseData.result.value!)

print("All Data JSON \(swiftyJsonVar)")

print("date range1\(swiftyJsonVar["date_range"])")

print("date range2\(swiftyJsonVar["date_range"].stringValue)")

print("jobs1 \(swiftyJsonVar["jobs"].arrayObject)")

print("jobs2 \(swiftyJsonVar["jobs"].array)")

print("jobs3 \(swiftyJsonVar["jobs"])")

print("jobs date \(swiftyJsonVar["jobs"]["date"].stringValue)")

print("jobs date \(swiftyJsonVar["jobs"]["job"]["drop_off_worker_id"].stringValue)")

}

输出,全部为空或为零All Data JSON除外(swiftyJsonVar)。我怎样才能得到date_rangedrop_off_worker_id的价值?我真的希望有人能帮助我。我花了很多时间来解决它,但仍然无法解决它。

回答:

你的JSON响应是Array而不是Dictionary,所以你需要访问它的第一个对象来获得你想要的细节。

if let dateRange = swiftyJsonVar[0]["date_range"].string { 

print(dateRange)

}

if let worker_id = swiftyJsonVar[0]["jobs"][0]["job"][0]["drop_off_worker_id"].int {

print(worker_id)

}

编辑:如果您有根多的对象比得到的所有dateRangeworker_id for循环。

for subJson in swiftyJsonVar.array { 

if let dateRange = subJson["date_range"].string {

print(dateRange)

}

for jobsJson in subJson["jobs"].array {

for jobJson in jobsJson["job"].array {

if let worker_id = jobJson["drop_off_worker_id"].int {

print(worker_id)

}

}

}

}

回答:

请尝试,通过引用数组中的元素的索引。

Alamofire.request(Constants.web_api+api_get_orders, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Constants.headers) 

.responseJSON { (responseData) -> Void in

if((responseData.result.value) != nil) {

let swiftyJsonVar = JSON(responseData.result.value!)

print("All Data JSON \(swiftyJsonVar)")

print("date range1\(swiftyJsonVar[0]["date_range"])")

print("date range2\(swiftyJsonVar[0]["date_range"].stringValue)")

print("jobs1 \(swiftyJsonVar[0]["jobs"].arrayObject)")

print("jobs2 \(swiftyJsonVar[0]["jobs"].array)")

print("jobs3 \(swiftyJsonVar[0]["jobs"])")

print("jobs date \(swiftyJsonVar[0]["jobs"]["date"].stringValue)")

print("jobs date \(swiftyJsonVar[0]["jobs"]["job"]["drop_off_worker_id"].stringValue)")

}

以上是 SwiftyJson从JSON 的全部内容, 来源链接: utcz.com/qa/261792.html

回到顶部