Swiftã§Jsonãç°¡åã«æ±ããã©ã¤ãã©ãªãswift-jsonããè¶ ä¾¿å©ï¼
æ®éã«ããã¨é¢åãããSwiftã«ãããJsonã®æ±ããè¶ ç°¡åã«ãªãã©ã¤ãã©ãªãswift-jsonãã®ç´¹ä»ã§ãï¼
swift-jsonã¨ã¯ï¼
Swiftã«ãããJsonã®æ±ããç°¡åã«ãã¦ãããã©ã¤ãã©ãªã§ãï¼
ä½è
ã®dankogaiããã«æè¬ã§ãï¼
ã»ããã¢ãã
https://github.com/dankogai/swift-json/blob/master/json/json.swift
ä¸è¨ã®ãã¼ã¸ã®json.swiftãä¸è¨ç»åã®ããã«èªèº«ã®ããã¸ã§ã¯ãã«é
ç½®ããã ãã§OKï¼è¶
ç°¡åï¼
使ãæ¹
ã¨ããããã³ã¼ãã示ãã¦ããï¼è©³ç´°ã説æãã¾ãï¼
以ä¸ã®ã³ã¼ãã§ã¯ï¼HeartRails Expressã¨ããé§
æ
å ±ãåå¾ã§ããAPIããæ°å®¿é§
ã®æ
å ±ãJsonå½¢å¼ã®ãã¼ã¿ãåãåãï¼å
容ã表示ãã¾ãï¼
// APIããJsonãåå¾ãã¦ãã¼ã¹ let json = JSON(url:"http://express.heartrails.com/api/json?method=getStations&name=%E6%96%B0%E5%AE%BF") // ç¹å®ã®è¦ç´ ã®åãåºã var line = json["response"]["station"][2]["line"] println("stationã®3çªç®ã®è¦ç´ ã®line: \(line)") // é åè¦ç´ ã®åãåºã for (i,station) in json["response"]["station"] { println("-----") for (key, value) in station { println("\(key): \(value)") } }
Jsonã®åå¾ã¨ãã¼ã¹
// APIããJsonãåå¾ãã¦ãã¼ã¹ let json = JSON(url:"http://express.heartrails.com/api/json?method=getStations&name=%E6%96%B0%E5%AE%BF")
æå®ããURLããJsonå½¢å¼ã®ãã¼ã¿ãåå¾ãã¾ãï¼ãã®ãµã³ãã«ã§ã©ã®ãããªãã¼ã¿ãåå¾ã§ãããã¯å®éã«URLã«ã¢ã¯ã»ã¹ãã¦ã¿ã¦ãã ããï¼
http://express.heartrails.com/api/json?method=getStations&name=%E6%96%B0%E5%AE%BF
ãããï¼JSON()
ã¨ããé¢æ°ã§ãã¼ã¹ãã¾ãï¼
ç¹å®ã®è¦ç´ ã®åãåºã
ããã§ã¯ãã¼ã¹ããå 容ãåå¾ãã¦ã¿ã¾ãããï¼
// ç¹å®ã®è¦ç´ ã®åãåºã var line = json["response"]["station"][2]["line"] println("stationã®3çªç®ã®è¦ç´ ã®line: \(line)")
ãããå®è¡ããã¨ä¸è¨ã®ããã«è¡¨ç¤ºããã¾ãï¼
stationã®3çªç®ã®è¦ç´ ã®line: JRå±±æç·
ã»ã¼è¦ãã¾ãã¾ã§ããï¼responseã®ä¸ã®stationé
åã®3çªç®ã®è¦ç´ ã®lineãåãåºãã¦ãã¾ãï¼
ãã®ããã«ãã¦ï¼å¥½ããªè¦ç´ ãç°¡åã«åå¾ã§ããã®ãswift-jsonã®ç´ æ´ãããã¨ããã§ãï¼
é åè¦ç´ ã®åãåºã
æå¾ã«ï¼é åè¦ç´ ãå ¨ã¦åãåºãæ¹æ³ãç´¹ä»ãã¦ããã¾ãï¼
// é åè¦ç´ ã®åãåºã for (i,station) in json["response"]["station"] { println("-----") for (key, value) in station { println("\(key): \(value)") } }
ãããå®è¡ããã¨ä»¥ä¸ã®ããã«è¡¨ç¤ºããã¾ãï¼
----- x: 139.700604 postal: 1600022 y: 35.690067 prefecture: æ±äº¬é½ next: å¤§ä¹ ä¿ line: JRä¸å¤®ç· name: æ°å®¿ prev: 代ã æ¨ ----- x: 139.700643 postal: 1600022 y: 35.689873 prefecture: æ±äº¬é½ next: æ± è¢ line: JRå¼äº¬ç· name: æ°å®¿ prev: æ¸è°· ----- x: 139.700643 postal: 1600022 y: 35.689873 prefecture: æ±äº¬é½ next: æ°å¤§ä¹ ä¿ line: JRå±±æç· name: æ°å®¿ prev: 代ã æ¨ ----- ...(以ä¸ç¥)
ãã®ããã«for in
ã«ã¼ãã§ç°¡åã«åãåºãã¾ãï¼
ãã ãï¼æ³¨æãã¦ã»ããã®ã¯ã¿ãã«ãç¨ãã¦åãåºãã¨ãããã¨ã§ãï¼
ä¸ã®ä¾ã§ã¯ï¼i
ã«ä½çªç®ã®è¦ç´ ããï¼station
ã«å®éã®è¦ç´ ãå
¥ã£ã¦ãã¾ãï¼
ãã®ä»ã®ä½¿ãæ¹
è±èªã§ããï¼GitHubã«è©³ãã説æãæ¸ããã¦ãã¾ãã®ã§ãã¡ããã©ããï¼
以ä¸ï¼Swiftã§Jsonãç°¡åã«æ±ããã©ã¤ãã©ãªãswift-jsonãã®ç´¹ä»ã§ããï¼
åè