使用SwiftyJSON处理JSON的示例

tat*_*ama 18 json ios swift xcode6

我想用SwiftJSON处理json,但我堆叠了.有没有人给我看示例代码?

我试图使用这个库. https://github.com/SwiftyJSON/SwiftyJSON

虽然我在同一个项目中放置了SwiftyJSON.swift,但我有错误"没有这样的模块"SwiftyJSON""所以纠正我的代码或者向我展示使用swiftyJSON lib从web处理json的示例代码.

这是我的代码:

import UIKit
import SwiftyJSON // No such module "SwiftyJSON"

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let url = NSURL(string: "http://express.heartrails.com/api/json?method=getPrefectures")

        var request = NSURLRequest(URL: url!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)

        var json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary

        var hoge = JSON(data)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的Xcode捕获

截图

rin*_*aro 25

如果添加SwiftyJSON.swift到项目中,则不需要import它.它已经可用了.

尝试:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://express.heartrails.com/api/json?method=getPrefectures")
        var request = NSURLRequest(URL: url!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
        if data != nil {
            var hoge = JSON(data: data!)
            println(hoge)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Oma*_*uqe 9

使用此https://github.com/SwiftyJSON/SwiftyJSON版本获取最新的SwiftyJSON

如果您想使用,import SwiftyJSON则需要添加使用pod来执行此操作,请按照步骤操作

  1. 打开终端并运行sudo gem install cocoapods安装cocoapods
  2. 从您的终端,到您的项目回家
  3. 运行pod init以初始化Podfile
  4. 打开Podfile并粘贴以下命令

platform :ios, '8.0' use_frameworks! target 'MyApp' do pod 'SwiftyJSON', '~> 2.2.1' end

  1. 最后运行pod install,它会将SwiftyJSON添加到您的项目中
  2. 关闭xcode并打开.xcworkspace而不是.xcodeproj

现在你很高兴

有关更多信息,请使用cocoapods中的SwiftyJSON