我有一个未命名的JSON数据,如下所示:
[
[
{
"job_title" : "job_title",
"fname" : "fname",
"department" : "department",
"email" : "",
"business_phone" : "business_phone",
"project" : null,
"location_id" : null,
"bio" : null,
"manager_id" : null,
"team_lead_id" : null,
"lname" : "lname",
"project_id" : null,
"title" : null,
"user_id" : 1,
"user_pass" : null,
"user_name" : "fname-lname",
"company" : "company",
"office_location_id" : "office_location"
},
{//Next employee record
//Data
}
]
]
我正在尝试使用Alamofire和SwiftyJSON将数据解析为一个字典,我将能够在应用程序的其他部分使用。
以下是我的尝试:
Alamofire.request(url, method: .post, encoding: JSONEncoding.default).validate().responseJSON{
response in
print("Request: \(String(describing: response.request))") // original URL request
print("Response: \(String(describing: response.response))") // HTTP URL response
print("Data: \(String(describing: response.data))") // server data
//print("Result: \(String(describing: response.result.value))") // result of response serialization
print("Error: \(String(describing: response.error))")
var json = JSON(response.result.value)
print(json)
//
// let fname: String = json[]["fname"].stringValue
// print(fname)
//
// for (index, object) in json {
// let fname = object["fname"].stringValue
// print(fname)
// }
// if let data = response.result.value?.data(using: String.Encoding.utf8){
// do {
// employeeDict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
//
// if let myDictionary = employeeDict{
// print("First name is: \(myDictionary["fname"]!)")
// }
// }
// }
// guard let object = response.result.value else{
// print("Error")
// return
// }
//
// let json = JSON(object)
// if let jsonArray = json.array{
// if let user_id = jsonArray[0]["user_id"].array{
// if let fname = jsonArray[1]["fname"].array{
// print(user_id)
// }
// }
// }
}
我可以打印出JSON数据,但无法访问任何信息或将任何信息存储在字典中。
答案 0 :(得分:0)
我没有使用SwiftyJSON,因为我使用JSONSerialization很好,所以我不知道你的json变量是什么数据类型,我也认为它是response.result.value类型为Data。
guard let json = try? JSONSerialization.jsonObject(with: response.result.value, options: .mutableContainers) else { return }
guard let rootArray = json as? Array<Array<Dictionary<String,Any>>> else { return }
let array = rootArray[0] // The outer/root array seems useless from what you have shown in your JSON above, so this is to get to the array of dictionaries.
for item in array {
print(item["job_title"]) // prints out "Optional(job_title)"
}