【发布时间】:2019-10-23 23:37:08
【问题描述】:
您好,我正在尝试获取更多关于如何从网站获取 JSON 代码然后对其进行解析的经验。 (见下面的代码)这有效,但我从苹果那里了解到这是一种“旧的,2017 年”的方式来做到这一点。而且我的字典有些问题,
问题1。如何在不使用任何其他 3rd 方方法或软件的情况下改进以下代码。
如何摆脱 Optional 语句,我只想打印 print(jsondata["title"]) 的值
我希望你能给我指明正确的方向。
谢谢罗恩
查看代码
'''
//: Playground - noun: a place where people can play
// put in some requirements to yse the playground
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
import Foundation
import UIKit
//just a check if I get some output in a variable and to see if the playground is working
var str = "this is a test to see if there is output"
// retrieve the data from a website and put it into an object called jsondata; print the size of jsondata in bytes and put it into a variable called data; put number of elements in jsondata into jsonelements
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
URLSession.shared.dataTask(with:url!, completionHandler: {(datasize, response, error) in
guard let data = datasize, error == nil else { return }
do {
let jsondata = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
//print the dictionary
print(jsondata)
// how many elements in the dictionary
let jsonelements = jsondata.count
print(jsonelements)
// Iterate through the dictionary and print the value per key
for (key,value) in jsondata {
print("\(key) = \(value)")
}
// get the values out of the dictionry
print(" ")
print(jsondata["title"])
print(jsondata["userID"])
print(jsondata["id"])
print(jsondata["completed"])
} catch let error as NSError {
print(error)
}
}).resume()
'''
// get the values out of the dictionry
print(" ")
print(jsondata["title"])
print(jsondata["userID"])
print(jsondata["id"])
print(jsondata["completed"])
在这里我得到一个警告“从'Any?'中隐式强制的表达式到任何
为什么我会收到警告? 以及如何在没有警告的情况下仅打印 print(jsondata["title"] 。 我认为我的做法是正确的
【问题讨论】: