gpt4 book ai didi

ios - 如何将 JSON 解析为 [String : AnyObject] in Swift

转载 作者:可可西里 更新时间:2023-11-01 02:15:23 27 4
gpt4 key购买 nike

我正在尝试执行一个简单的 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”。

我想避免使用第三方库。

最佳答案

Sample Json Parsing Fetch and 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())!)!

关于ios - 如何将 JSON 解析为 [String : AnyObject] in Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39177492/

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