【发布时间】:2019-01-05 19:54:12
【问题描述】:
检索键值的例子有很多,我可以做到。在这种情况下,键有多个值。关键是“挖矿”,后面跟着6个值。同一个 key:value 重复 30 次,当然 key 的值不同。
我似乎无法解决的是如何返回值。尤其是第一个,例如 1532825277682891390,它似乎是一个带有与其相关的键/值对的子键。
The todo is: ["mining": {
1532825277682891390 = {
command = mining;
siteid = "Platform Mining";
ts = 1532825270557;
user1 = 73276;
value = 1;
};
1532826406100318457 = {
command = mining;
siteid = "Platform Mining";
ts = 1532826375712;
user1 = 73276;
value = 1;
};
1532827074955562013 = {
command = mining;
siteid = "Platform Mining";
ts = 1532827066645;
user1 = 73276;
value = 1;
};
153282775791322835 = {
command = mining;
siteid = "Platform Mining";
ts = 1532827753205;
user1 = 73276;
value = 1;
};
....
....
....
}
我可以显示“挖掘”键的键:值。字典里只有两个键,'mining'和'success'——我不担心'success',它通常返回'1'。
这基本上是带有一些示例和试验输出的代码,因为我尝试了与其他帖子不同的东西。我只是无法理解这一点。 我是否需要将字典放入数组中,我该怎么做,或者我可以将每个值放入 var 中,这样我就可以将它们打印到 UITabDisplay 中?
func makeGetCall() {
// Set up the URL request
let todoEndpoint: String = "https://api.jsecoin.com/v1.7/mining/auth/"
let apiKey = "xxxxxxxxxxxxxxxxxxxxxxx"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
var urlRequest = URLRequest(url: url)
urlRequest.setValue(apiKey, forHTTPHeaderField: "Authorization")
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
print("Got data: \(responseData)")
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo
// let's just print it to prove we can access it
print("The todo is: " + todo.description)
// from this point on I"m experimenting ....
let dict = todo.description
print("The dict is: " + dict)
let keys = Array(todo.keys)
// prints ["mining", "success"]
print(keys)
/////////////////////////////////
if let alb = todo["mining"] {
// prints all the values for 'mining'.
// {
// 1532825277682891390 = {
// command = mining;
// siteid = "Platform Mining";
// ts = 1532825270557;
// user1 = 73276;
// value = 1;
// };
// ........ 30 entires
print(alb)
}
//======================
let index1 = todo.index(forKey: "mining")
let myMining = (todo[index1!].value)
// again prints all the mining values. Mining: {
// 1532825277682891390 = {
// command = mining;
// siteid = "Platform Mining";
// ts = 1532825270557;
// user1 = 73276;
// value = 1;
// };
print("Mining: \(myMining)")
//============
【问题讨论】:
标签: ios json dictionary swift4