第三方api JSON抓取練習-Random
用 playground練習
Random User Generator
https://randomuser.me/
這個網頁是隨機用戶產生器
一次取十個用戶
https://randomuser.me/api/?results=10
連結到上列網址會出現一個json檔案
將內容 copy 到這個網頁來看它的階層
第一層
struct First: Codable {
let results: []
}
第二層
我選 gender name email phone
struct Second: Codable {
let gender: String
let name: []
let email: String
let phone: String
}
let name: []是另外一層,所以暫時給它個[ ]
第三層
這一層是要解 name
struct ThirdName: Codable {
let title: String
let first: String
let last: String
}
第三層寫好之後,要記得將第三層的ThirdName改到第二層的 name
name: []的中括號不需要,因為name包的是大括號
而 results: [Second]要加中括號,是因為它的資料是用 [ ]包起來
struct First: Codable {
let results: [Second]
}
struct Second: Codable {
let gender: String
let name: ThirdName
let email: String
let phone: String
}
struct ThirdName: Codable {
let title: String
let first: String
let last: String
}
解析資料
我想抓的資料是 firstname 跟 lestname
struct First: Codable {
let results: [Second]
}
struct Second: Codable {
let gender: String
let name: ThirdName
let email: String
let phone: String
}
struct ThirdName: Codable {
let title: String
let first: String
let last: String
}
let urlString = "https://randomuser.me/api/?results=10"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url){
data, response, error in
if let data{
let decode = JSONDecoder()
do {
let first = try decode.decode(First.self, from: data)
let itemSecond = first.results[0]
print(itemSecond.name.first, itemSecond.name.last)
} catch {
print(error)
}
}
}.resume()
}
0929jsonDemo-Random