json - 检索 JSON 数据然后解析它(需要一些帮助)

标签 json swift api swift4.2

您好,我正在尝试获得更多关于如何从网站获取 JSON 代码然后解析它的经验。 (见下面的代码)这是有效的,但我从苹果那里了解到这是一种“旧的,2017 年”的方法。我在使用字典时遇到了一些问题,

问题1。如何在不使用任何其他第 3 方方法或软件的情况下改进下面的代码。

如何去掉 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"] 。 我认为我的做法是正确的

最佳答案

要消除警告并打印出没有可选的值,请使用 if let 如下所示。

if let title = jsondata["title"] {
   print(title)
}

你也可以使用 guard let 来做到这一点

guard let title = jsondata["title"] else { return }
print(title)

如果你是 100% 的返回类型并且它不会是 nil 使用 guard let 或

print(jsondata["title"] as! String)

但是,不推荐使用上面的示例,因为您通常不想强制解包(!)

关于警告和另一个例子 -> https://stackoverflow.com/a/40691455/9578009

关于json - 检索 JSON 数据然后解析它(需要一些帮助),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56511651/

相关文章:

ios - 合并冲突核心数据

xcode - 添加计时器接收iAd Interstitial(Xcode,swift)

api - Yammer api : Get messages by group

javascript - javascript中根据key合并对象

json - 使用 Serde 反序列化嵌套 JSON 结构时出现 "invalid type: map, expected a sequence"

android - 如何为动态 key 解析此类 JSON 数据

ios - 当用户在 iOS 的 UITextField 中输入值时,可以不断更新 UILabel 文本

java - 了解 Twitter API

用于使用 Skype API 的 Java 库

javascript - 接收由 jQuery 发送并由 Node Js 接收的 JSON 形式的数组表单数据