Djsonファイルを他のアプリに流用したく色々試しましたが、print文で表示ができるようになったものの、データーの取得ができませんでした。どのようにすれば良いかご教授ください。
swift3
1import UIKit 2 3class ViewController: UIViewController { 4 5 6 override func viewDidLoad() { 7 super.viewDidLoad() 8 9 let path : String = Bundle.main.path(forResource: "assets/sg/index0", ofType: "json")! 10 let fileHandle : FileHandle = FileHandle(forReadingAtPath: path)! 11 let data : NSData = fileHandle.readDataToEndOfFile() as NSData 12 let jsonStr = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) 13 print(jsonStr!) 14 15 16 } 17} 18
jsonファイルは下記です。"北海道・東北"ならば3つの七福神の名前とナンバーを取得したく、"関東"だったら8つの七福神の名前とナンバーを取得したい。データは本来はもっとあります。サンプルデータを載せます。
json
1{ 2 "北海道・東北" : [ 3 { 4 "name" : "奥州仙臺七福神" , "number" : 0 5 } , { 6 "name" : "会津七福神" , "number" : 1 7 } , { 8 "name" : "出羽七福神" , "number" : 2 9 } 10 ] , 11 "関東" : [ 12 { 13 "name" : "とりで利根川七福神" , "number" : 3 14 } , { 15 "name" : "奥久慈大子七福神" , "number" : 4 16 } , { 17 "name" : "常陸七福神" , "number" : 5 18 } , { 19 "name" : "足利七福神" , "number" : 6 20 } , { 21 "name" : "八溝七福神" , "number" : 7 22 } , { 23 "name" : "横浜磯子七福神" , "number" : 8 24 } , { 25 "name" : "横浜七福神" , "number" : 9 26 } , { 27 "name" : "横浜瀬谷八福神" , "number" : 10 28 } 29 ] 30}
大変忙しいところ申し訳ありませんが、宜しくお願い致します。
自分なりに変換したソース
swift3
1do { 2 let jsonArray:NSArray = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray 3 print(jsonArray) 4 } catch { 5 print(error) 6 }
swift3のソースで
swift
1do{ 2 let jsonArray:NSArray = try JSONSerialization.jsonObject(with: data as Data , options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray 3 print(jsonArray) 4 5 } catch { 6 7 }
とすると実行エラーが発生しました。
Could not cast value of type '__NSDictionaryM' (0x10d5aa2b0) to 'NSArray' (0x10d5a9e28).
でNSArrayをNSDictionaryに変更して実行しますとエラーは発生しないのですが、表示がおかしくなります
swift
1do{ 2 let jsonArray:NSDictionary = try JSONSerialization.jsonObject(with: data as Data , options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary 3 print(jsonArray) 4 5 } catch { 6 7 }
printの結果
{ "\U5317\U6d77\U9053\U30fb\U6771\U5317" = ( { name = "\U5965\U5dde\U4ed9\U81fa\U4e03\U798f\U795e"; number = 0; }, { name = "\U4f1a\U6d25\U4e03\U798f\U795e"; number = 1; }, { name = "\U51fa\U7fbd\U4e03\U798f\U795e"; number = 2; } ); "\U95a2\U6771" = ( { name = "\U3068\U308a\U3067\U5229\U6839\U5ddd\U4e03\U798f\U795e"; number = 3; }, { name = "\U5965\U4e45\U6148\U5927\U5b50\U4e03\U798f\U795e"; number = 4; }, { name = "\U5e38\U9678\U4e03\U798f\U795e"; number = 5; }, { name = "\U8db3\U5229\U4e03\U798f\U795e"; number = 6; }, { name = "\U516b\U6e9d\U4e03\U798f\U795e"; number = 7; }, { name = "\U6a2a\U6d5c\U78ef\U5b50\U4e03\U798f\U795e"; number = 8; }, { name = "\U6a2a\U6d5c\U4e03\U798f\U795e"; number = 9; }, { name = "\U6a2a\U6d5c\U702c\U8c37\U516b\U798f\U795e"; number = 10; } ); }
となります。
回答1件
あなたの回答
tips
プレビュー