gpt4 book ai didi

json - 解析 swift 3 中的嵌套 Json 数据

转载 作者:行者123 更新时间:2023-11-30 12:10:31 24 4
gpt4 key购买 nike

当我从 api 解析 json 数据时,我得到了意想不到的值,我可能在这里做错了什么,因为我对 swift 很陌生,但在我收到一个“ key ”之前,我得到了正确的值但现在我添加了两个,我似乎无法正确解析这些值。

这是从我的代码接收的地址收集的 json,(抱歉,如果它很难阅读,还没有弄清楚如何在我的 ruby​​ api 中进行换行)(只要它的功能我不太担心)此刻)

           {
"ratings":{
"elements":{"Ready Position":[{"description":"Neutral Grip","values":"1,2,3,4,5"},{"description":"Back Straight (Concave ir Convex?)","values":"1,2,3,4,5"},{"description":"Body Low \u0026 Feet a little more than sholder width apart","values":"1,2,3,4,5"},{"description":"Weight on Balls of Feet","values":"1,2,3,4,5"},{"description":"Head Up","values":"1,2,3,4,5"},{"description":"Sholder Blades Close","values":"1,2,3,4,5"},{"description":"Eyes Drilled","values":"1,2,3,4,5"}],"Split Step":[{"description":"Ready Position Conforms","values":"Yes,No"},{"description":"Body Position Low","values":"1,2,3,4,5"},{"description":"Legs Loaded/Prepared","values":"1,2,3,4,5"}]}
},
"comments":{}
}

现在,我的 swift 代码如下所示

 let playerAPIurl = "http://linkcoachuat.herokuapp.com/api/v1/session/element?organisation=" + userorganisation + "&group=" + urlGroupSelected + "&sport=" + usersport
print(playerAPIurl)
var request = URLRequest(url: URL(string: playerAPIurl)!)
request.httpMethod = "GET"



let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

let task = session.dataTask(with: request) { (data, response, error) in
if error != nil {
print("ERROR")
}
else{

do {


let json = try JSONSerialization.jsonObject(with: data!) as? [String: AnyObject]

print(json)

这是我从 print(json) 得到的输出

Optional({
comments = {
};
ratings = {
};
})

我知道我不应该在评论部分得到更多的东西,但是在评级部分应该有一些数据?

所以在收到 json 并处理解析它之后,我需要访问它的这一部分 [“评级”] [“元素”],之后我一切都很好

提前致谢,请在我的中裸露,我对 Swift 很陌生

谢谢

最佳答案

尝试下面的代码。下面代码中使用的 url 包含您的 JSON 数据。此代码正确打印输出。

 func testApi(){
let url = URL(string: "https://api.myjson.com/bins/jfccx")

let session = URLSession.shared
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 let data = data, error == nil else {
return
}

do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
print(json)
}

} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}

output

关于json - 解析 swift 3 中的嵌套 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46133239/

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