hi,我正试图获得更多有关如何从网站获取JSON代码然后进行解析的经验。 (请参见下面的代码),这是可行的,但我从苹果公司了解到,这是一种“古老的,2017年”的方法。而且我的字典有些问题,
问题1。在不使用任何其他第三方方法或软件的情况下,如何改进下面的代码。
我如何摆脱Optional语句,而只想打印print(jsondata [“ title”])
的值我希望您能为我设定正确的方向。
thx罗恩
查看代码
'''
//: 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"])
在这里我得到一个警告:“任何人都隐含地强迫了表达式?”对任何人
为什么收到警告? 以及如何在没有警告的情况下仅打印print(jsondata [“ title”]。 我想我做对了
答案 0 :(得分:0)
要消除警告并打印出没有可选值的值,请按照以下说明进行操作。
if let title = jsondata["title"] {
print(title)
}
您也可以使用警卫队让步
guard let title = jsondata["title"] else { return }
print(title)
如果您是返回类型的100%并且不会为零,请使用guard let或
print(jsondata["title"] as! String)
但是,不建议使用上面的示例,因为您通常不希望强制进行unwrap(!)
关于警告和另一个示例-> https://stackoverflow.com/a/40691455/9578009
答案 1 :(得分:0)
完成此操作的标准方法是声明一个类型并按如下方式使用它,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header class="tw-z-50">
<div class="nav-down">
</div>
<div class="tw-w-full">
<div class="scroll-progress-bar"></div>
</div>
</header>
<div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div><div>This is a test</div>
答案 2 :(得分:0)
问题1。在不使用任何其他第三方方法或软件的情况下,如何改进下面的代码。
使用Decodable
,它将数据直接解码为结构。没有可选项,没有Any
。
//: 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
struct ToDo : Decodable {
let userId, id : Int
let title : String
let completed : Bool
}
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
URLSession.shared.dataTask(with:url) { data, _, error in
guard let data = data else { print(error!); return }
do {
let todo = try JSONDecoder().decode(ToDo.self, from: data)
// get the values out of the struct
print(" ")
print(todo.title)
print(todo.userId)
print(todo.id)
print(todo.completed)
} catch {
print(error)
}
}.resume()