我正在尝试对Object进行简单的JSON字符串转换。这是代码:
let u = "somehost.com/api/1/ipa/2"
let url = NSURL(string: u )!
let data = NSData(contentsOfURL: url)!
let parsed: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
if let json = parsed as? [String: AnyObject]{
// never enters this if statement.
}
但它不能正确解开。在我看来,这应该简单得多。有人可以帮忙吗?还使用" Xcode 7.3和swift 2.2"。
我想避免使用第三方库。
答案 0 :(得分:1)
示例Json Parsing Fetch和read这样简单易懂的理解过程。点击下面的链接,你会看到响应为字典,在字典里面有一个数组.......
let WebURL = "http://api.randomuser.me/"
let url2 = NSURL(string:WebURL)
let data = NSData(contentsOfURL: url2!)
do
{
let dictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSMutableDictionary
print(dictionary)
let arrayOfValues = dictionary .objectForKey("results") as! NSMutableArray
print(arrayOfValues)
for var i = 0; i<arrayOfValues.count; i++ {
let resultDictInsideArray = arrayOfValues.objectAtIndex(i)
let NameDict = resultDictInsideArray.objectForKey("name")!
let locDict = resultDictInsideArray.objectForKey("location")!
print(NameDict.objectForKey("title")!)
print(locDict.objectForKey("street")!)
}
}catch {
print("error")
}
如果您的网址有空格,请像这样编写网址代码
let url = NSURL(string: stringUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)!
答案 1 :(得分:0)
您确定返回的内容不是数组而不是对象吗?
你试过这个:
if let json = parsed as? [AnyObject]{
}
答案 2 :(得分:0)
func getDataFromServer(myGetUrl : URL) {
let url = myGetUrl
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
let request = URLRequest(url: url )
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
print(error as Any)
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:AnyObject]] {
//print(json)
self.getResponsedata = json
//print("Here: \(self.getResponsedata)")
self.getDelegate.GetdataReceivedFromServer(data: self.getResponsedata , url : myGetUrl)
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
}