前提・実現したいこと
teratailのAPIを叩いて、質問一覧を取得したいです。
ライブラリはAlamofire
, swiftyJSON
を使用しています。
下記の通りコードを書きましたが、display_name
とtags
のみデータ取得できないです。
画像の通り、""
,[]
となってしまいます。
下記の通りprintすると問題なく、出力されますため、恐らくQuestionファイルに問題があると思っているのですが、何が原因なのか分からず苦慮しています。
どなたか原因ご教示いただけないでしょうか?
print(json[Const.user][Const.displayName]) print(json[Const.tags])
JSON構造
JSON
1{ 2 meta:{ 3 message: "success", 4 total_page: 11734, 5 page: 1, 6 limit: 20, 7 hit_num: 234677 8}, 9questions:[ 10 { 11 id: 237853, 12 title: "ELB+EC2+nginx+express環境でhttps対応をしたがバックエンドが動かない", 13 created: "2020-01-27 19:45:04", 14 modified: "2020-01-27 19:45:04", 15 count_reply: 0, 16 count_clip: 0, 17 count_pv: 4, 18 is_beginner: false, 19 is_accepted: false, 20 is_presentation: false, 21 tags:["nginx", "Amazon EC2", "AWS(Amazon Web Services)", "HTTPS", "Express"], 22 user:{ 23 display_name: "aqaqsanba", 24 photo: "https://teratail-v2.storage.googleapis.com/uploads/avatars/u13/138880/gI0ELDZK_thumbnail.jpg", 25 score: 0 26 } 27},
該当のソースコード
Const
1struct Const { 2 static let id = "id" 3 static let title = "title" 4 static let tags = "tags" 5 static let user = "user" 6 static let displayName = "display_name" 7 static let photo = "photo" 8}
Question
1struct Question { 2 let id: Int 3 let title: String 4 let tags: [String] 5 let displayName: String 6 let photo: String 7 8 init(json: [String: Any]) { 9 id = json[Const.id] as? Int ?? 0 10 title = json[Const.title] as? String ?? "" 11 tags = json[Const.tags] as? [String] ?? [] 12 displayName = json[Const.displayName] as? String ?? "" 13 photo = json[Const.photo] as? String ?? "" 14 } 15}
QuestionListViewController
1var questions: [Question] = [] { 2 didSet { 3 questionListTableView.reloadData() 4 } 5} 6 7func getQuestions() { 8 Alamofire.request("https://teratail.com/api/v1/questions").responseJSON { response in 9 guard let object = response.result.value else { 10 return 11 } 12 let json = JSON(object) 13 json["questions"].forEach { (_, json) in 14 let question: [String: Any] = 15 ["id": json[Const.id].intValue, 16 "title": json[Const.title].stringValue, 17 "tags": json[Const.tags].arrayValue, 18 "displayName": json[Const.displayName][Const.displayName].stringValue, 19 "photo": json[Const.user][Const.photo].stringValue 20 ] 21 self.questions.append(Question(json: question)) 22 } 23 print(self.questions) 24 } 25 }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/28 09:48