質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Twitter

Twitterは、140文字以内の「ツイート」と呼ばれる短文を投稿できるサービスです。Twitter上のほぼ全ての機能に対応するAPIが存在し、その関連サービスが多く公開されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

2387閲覧

SwiftでJSONパース

gtime

総合スコア51

JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Twitter

Twitterは、140文字以内の「ツイート」と呼ばれる短文を投稿できるサービスです。Twitter上のほぼ全ての機能に対応するAPIが存在し、その関連サービスが多く公開されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2017/04/08 09:26

編集2017/04/14 04:13

swift

1import UIKit 2import TwitterKit 3 4class ViewController: UIViewController { 5 6 override func viewDidLoad() { 7 super.viewDidLoad() 8 self.setNeedsStatusBarAppearanceUpdate(); 9 let logInButton = TWTRLogInButton { (session, error) in 10 if let unwrappedSession = session { 11 let alert = UIAlertController(title: "Logged In", 12 message: "User \(unwrappedSession.userName) has logged in", 13 preferredStyle: UIAlertControllerStyle.alert 14 ) 15 alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) 16 self.present(alert, animated: true, completion: nil) 17 18 } else { 19 print("Login error: %@", error!.localizedDescription); 20 } 21 } 22 logInButton.loginMethods = [.webBased] 23 24 let button = logInButton 25 button.center = self.view.center 26 self.view.addSubview(button) 27 //ここからツイート投稿のための準備 28 let endpoint = "https://api.twitter.com/1.1/statuses/home_timeline.json" 29 30 let client = TWTRAPIClient.init(userID: "111111111") 31 32 var clientError : NSError? 33 34 let params = ["count": "10"] 35 36 let request = client.urlRequest(withMethod: "GET", url: endpoint, parameters: params, error: &clientError) 37 38 client.sendTwitterRequest(request) { 39 (response, data, connectionError) -> Void in 40 if connectionError != nil { 41 print("エラー: \(connectionError)") 42 } else { 43 44 let json: AnyObject? = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? 45 print(json!) 46 } 47 } 48 49 } 50}

このようにTwitterのタイムラインのJSONを受信することはできたのですが、Swiftでforeachで配列を回して、ツイート本文やユーザーネームを取り出して表示するにはどのようにすればいいのでしょうか?

JSONはこのような感じです
[
{
"place" : null,
"contributors" : null,
"source" : "<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>",
"truncated" : false,
"is_quote_status" : false,
"favorite_count" : 0,
"lang" : "ja",
"entities" : {
"symbols" : [

], "user_mentions" : [ ], "urls" : [ ], "hashtags" : [ ] }, "in_reply_to_screen_name" : null, "retweet_count" : 0, "favorited" : false, "geo" : null, "id" : 852734851786579974, "user" : { "protected" : false, "is_translator" : false, "profile_image_url" : "http:\/\/pbs.twimg.com\/profile_images\/850998804878774272\/-bABtccG_normal.jpg", "created_at" : "Mon Apr 05 08:12:28 +0000 2010", "id" : 129746204, "default_profile_image" : false, "listed_count" : 1542, "profile_background_color" : "131516", "follow_request_sent" : false, "location" : "PSO2", "entities" : { "url" : { "urls" : [ { "url" : "http:\/\/www.pixiv.net\/member.php?id=76712", "indices" : [ 0, 40 ], "expanded_url" : null } ] }, "description" : { "urls" : [ { "display_url" : "ask.fm\/patrietta", "url" : "https:\/\/t.co\/fLNYk70nQJ", "indices" : [ 67, 90 ], "expanded_url" : "http:\/\/ask.fm\/patrietta" } ] } }, "url" : "http:\/\/www.eeee.net\/member.php", "description" : "とあるuser", "followers_count" : 69707, "geo_enabled" : false, "lang" : "ja", "profile_text_color" : "333333", "statuses_count" : 55066, "following" : true, "notifications" : false, "profile_background_tile" : true, "profile_use_background_image" : true, "id_str" : "129746204", "name" : "あるuser", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/850998804878774272\/-yff8f6fyh.jpg", "profile_sidebar_fill_color" : "EFEFEF", "profile_sidebar_border_color" : "FFFFFF", "contributors_enabled" : false, "default_profile" : false, "profile_banner_url" : "https:\/\/pbs.twimg.com\/profile_banners\/129746204\/1471936684", "screen_name" : "ここがスクリーンネーム", "time_zone" : "Tokyo", "profile_background_image_url" : "http:\/\/pbs.twimg.com\/profile_background_images\/454304509376741376\/lTp51aDO.jpeg", "profile_background_image_url_https" : "https:\/\/pbs.twimg.com\/profile_background_images\/454304509376741376\/lTp51aDO.jpeg", "profile_link_color" : "F5ABB5", "favourites_count" : 3889, "is_translation_enabled" : false, "translator_type" : "none", "utc_offset" : 32400, "friends_count" : 1233, "verified" : false, "has_extended_profile" : true }, "in_reply_to_user_id" : null, "retweeted" : false, "text" : "ツイート本文", "created_at" : "Fri Apr 14 04:06:46 +0000 2017", "in_reply_to_status_id_str" : null, "in_reply_to_status_id" : null, "in_reply_to_user_id_str" : null, "id_str" : "852734851786579974", "coordinates" : null

}
]

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

fuzzball

2017/04/10 02:28

ダミーのJSONなどを用意して、こちらで再現出来るようにして下さい。
gtime

2017/04/14 04:15

ありがとうございます。JSONを追加しました
guest

回答1

0

ベストアンサー

swift

1let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String:Any]] 2 3for obj in json { 4 //screen_name 5 if let user = obj["user"] as? [String:Any] { 6 let screen_name = user["screen_name"] ?? "(empty)" 7 print("screen_name =", screen_name) 8 } else { 9 print("does not exist 'user'") 10 } 11 //text 12 let text = obj["text"] ?? "(empty)" 13 print("text =", text) 14}

投稿2017/04/14 04:53

fuzzball

総合スコア16731

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

gtime

2017/04/14 07:46

ありがとうございます パースすることができました
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問