Coder Social home page Coder Social logo

swiftyjson / alamofire-swiftyjson Goto Github PK

View Code? Open in Web Editor NEW
1.4K 1.4K 173.0 47 KB

Alamofire extension for serialize NSData to SwiftyJSON

License: MIT License

Ruby 11.46% Swift 78.28% Objective-C 10.25%
alamofire alamofire-swiftyjson swift swiftyjson

alamofire-swiftyjson's Introduction

SwiftyJSON

Carthage compatible CocoaPods Platform Reviewed by Hound

SwiftyJSON makes it easy to deal with JSON data in Swift.

Platform Build Status
*OS Travis CI
Linux Build Status
  1. Why is the typical JSON handling in Swift NOT good
  2. Requirements
  3. Integration
  4. Usage
  5. Work with Alamofire
  6. Work with Moya
  7. SwiftyJSON Model Generator

Why is the typical JSON handling in Swift NOT good?

Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types.

Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API).

The code would look like this:

if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
    let user = statusesArray[0]["user"] as? [String: Any],
    let username = user["name"] as? String {
    // Finally we got the username
}

It's not good.

Even if we use optional chaining, it would be messy:

if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
    let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String {
        // There's our username
}

An unreadable mess--for something that should really be simple!

With SwiftyJSON all you have to do is:

let json = try? JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
  //Now you got your value
}

And don't worry about the Optional Wrapping thing. It's done for you automatically.

let json = try? JSON(data: dataFromNetworking)
let result = json[999999]["wrong_key"]["wrong_name"]
if let userName = result.string {
    //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety
} else {
    //Print the error
    print(result.error)
}

Requirements

  • iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+
  • Xcode 8

Integration

CocoaPods (iOS 8+, OS X 10.9+)

You can use CocoaPods to install SwiftyJSON by adding it to your Podfile:

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
    pod 'SwiftyJSON', '~> 4.0'
end

Carthage (iOS 8+, OS X 10.9+)

You can use Carthage to install SwiftyJSON by adding it to your Cartfile:

github "SwiftyJSON/SwiftyJSON" ~> 4.0

If you use Carthage to build your dependencies, make sure you have added SwiftyJSON.framework to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase.

Swift Package Manager

You can use The Swift Package Manager to install SwiftyJSON by adding the proper description to your Package.swift file:

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    dependencies: [
        .package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", from: "4.0.0"),
    ]
)

Then run swift build whenever you get prepared.

Manually (iOS 7+, OS X 10.9+)

To use this library in your project manually you may:

  1. for Projects, just drag SwiftyJSON.swift to the project tree
  2. for Workspaces, include the whole SwiftyJSON.xcodeproj

Usage

Initialization

import SwiftyJSON
let json = try? JSON(data: dataFromNetworking)

Or

let json = JSON(jsonObject)

Or

if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) {
    let json = JSON(data: dataFromString)
}

Subscript

// Getting a double from a JSON Array
let name = json[0].double
// Getting an array of string from a JSON Array
let arrayNames =  json["users"].arrayValue.map {$0["name"].stringValue}
// Getting a string from a JSON Dictionary
let name = json["name"].stringValue
// Getting a string using a path to the element
let path: [JSONSubscriptType] = [1,"list",2,"name"]
let name = json[path].string
// Just the same
let name = json[1]["list"][2]["name"].string
// Alternatively
let name = json[1,"list",2,"name"].string
// With a hard way
let name = json[].string
// With a custom way
let keys:[JSONSubscriptType] = [1,"list",2,"name"]
let name = json[keys].string

Loop

// If json is .Dictionary
for (key,subJson):(String, JSON) in json {
   // Do something you want
}

The first element is always a String, even if the JSON is an Array

// If json is .Array
// The `index` is 0..<json.count's string value
for (index,subJson):(String, JSON) in json {
    // Do something you want
}

Error

SwiftyJSON 4.x

SwiftyJSON 4.x introduces an enum type called SwiftyJSONError, which includes unsupportedType, indexOutOfBounds, elementTooDeep, wrongType, notExist and invalidJSON, at the same time, ErrorDomain are being replaced by SwiftyJSONError.errorDomain. Note: Those old error types are deprecated in SwiftyJSON 4.x and will be removed in the future release.

SwiftyJSON 3.x

Use a subscript to get/set a value in an Array or Dictionary

If the JSON is:

  • an array, the app may crash with "index out-of-bounds."
  • a dictionary, it will be assigned to nil without a reason.
  • not an array or a dictionary, the app may crash with an "unrecognised selector" exception.

This will never happen in SwiftyJSON.

let json = JSON(["name", "age"])
if let name = json[999].string {
    // Do something you want
} else {
    print(json[999].error!) // "Array[999] is out of bounds"
}
let json = JSON(["name":"Jack", "age": 25])
if let name = json["address"].string {
    // Do something you want
} else {
    print(json["address"].error!) // "Dictionary["address"] does not exist"
}
let json = JSON(12345)
if let age = json[0].string {
    // Do something you want
} else {
    print(json[0])       // "Array[0] failure, It is not an array"
    print(json[0].error!) // "Array[0] failure, It is not an array"
}

if let name = json["name"].string {
    // Do something you want
} else {
    print(json["name"])       // "Dictionary[\"name"] failure, It is not an dictionary"
    print(json["name"].error!) // "Dictionary[\"name"] failure, It is not an dictionary"
}

Optional getter

// NSNumber
if let id = json["user"]["favourites_count"].number {
   // Do something you want
} else {
   // Print the error
   print(json["user"]["favourites_count"].error!)
}
// String
if let id = json["user"]["name"].string {
   // Do something you want
} else {
   // Print the error
   print(json["user"]["name"].error!)
}
// Bool
if let id = json["user"]["is_translator"].bool {
   // Do something you want
} else {
   // Print the error
   print(json["user"]["is_translator"].error!)
}
// Int
if let id = json["user"]["id"].int {
   // Do something you want
} else {
   // Print the error
   print(json["user"]["id"].error!)
}
...

Non-optional getter

Non-optional getter is named xxxValue

// If not a Number or nil, return 0
let id: Int = json["id"].intValue
// If not a String or nil, return ""
let name: String = json["name"].stringValue
// If not an Array or nil, return []
let list: Array<JSON> = json["list"].arrayValue
// If not a Dictionary or nil, return [:]
let user: Dictionary<String, JSON> = json["user"].dictionaryValue

Setter

json["name"] = JSON("new-name")
json[0] = JSON(1)
json["id"].int =  1234567890
json["coordinate"].double =  8766.766
json["name"].string =  "Jack"
json.arrayObject = [1,2,3,4]
json.dictionaryObject = ["name":"Jack", "age":25]

Raw object

let rawObject: Any = json.object
let rawValue: Any = json.rawValue
//convert the JSON to raw NSData
do {
	let rawData = try json.rawData()
  //Do something you want
} catch {
	print("Error \(error)")
}
//convert the JSON to a raw String
if let rawString = json.rawString() {
  //Do something you want
} else {
	print("json.rawString is nil")
}

Existence

// shows you whether value specified in JSON or not
if json["name"].exists()

Literal convertibles

For more info about literal convertibles: Swift Literal Convertibles

// StringLiteralConvertible
let json: JSON = "I'm a json"
// IntegerLiteralConvertible
let json: JSON =  12345
// BooleanLiteralConvertible
let json: JSON =  true
// FloatLiteralConvertible
let json: JSON =  2.8765
// DictionaryLiteralConvertible
let json: JSON =  ["I":"am", "a":"json"]
// ArrayLiteralConvertible
let json: JSON =  ["I", "am", "a", "json"]
// With subscript in array
var json: JSON =  [1,2,3]
json[0] = 100
json[1] = 200
json[2] = 300
json[999] = 300 // Don't worry, nothing will happen
// With subscript in dictionary
var json: JSON =  ["name": "Jack", "age": 25]
json["name"] = "Mike"
json["age"] = "25" // It's OK to set String
json["address"] = "L.A." // Add the "address": "L.A." in json
// Array & Dictionary
var json: JSON =  ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]]
json["list"][3]["what"] = "that"
json["list",3,"what"] = "that"
let path: [JSONSubscriptType] = ["list",3,"what"]
json[path] = "that"
// With other JSON objects
let user: JSON = ["username" : "Steve", "password": "supersecurepassword"]
let auth: JSON = [
  "user": user.object, // use user.object instead of just user
  "apikey": "supersecretapitoken"
]

Merging

It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the other JSON.

If both JSONs contain a value for the same key, mostly this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment:

  • In case of both values being a JSON.Type.array the values form the array found in the other JSON getting appended to the original JSON's array value.
  • In case of both values being a JSON.Type.dictionary both JSON-values are getting merged the same way the encapsulating JSON is merged.

In a case where two fields in a JSON have different types, the value will get always overwritten.

There are two different fashions for merging: merge modifies the original JSON, whereas merged works non-destructively on a copy.

let original: JSON = [
    "first_name": "John",
    "age": 20,
    "skills": ["Coding", "Reading"],
    "address": [
        "street": "Front St",
        "zip": "12345",
    ]
]

let update: JSON = [
    "last_name": "Doe",
    "age": 21,
    "skills": ["Writing"],
    "address": [
        "zip": "12342",
        "city": "New York City"
    ]
]

let updated = original.merge(with: update)
// [
//     "first_name": "John",
//     "last_name": "Doe",
//     "age": 21,
//     "skills": ["Coding", "Reading", "Writing"],
//     "address": [
//         "street": "Front St",
//         "zip": "12342",
//         "city": "New York City"
//     ]
// ]

String representation

There are two options available:

  • use the default Swift one
  • use a custom one that will handle optionals well and represent nil as "null":
let dict = ["1":2, "2":"two", "3": nil] as [String: Any?]
let json = JSON(dict)
let representation = json.rawString(options: [.castNilToNSNull: true])
// representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null}

Work with Alamofire

SwiftyJSON nicely wraps the result of the Alamofire JSON response handler:

Alamofire.request(url, method: .get).validate().responseJSON { response in
    switch response.result {
    case .success(let value):
        let json = JSON(value)
        print("JSON: \(json)")
    case .failure(let error):
        print(error)
    }
}

We also provide an extension of Alamofire for serializing NSData to SwiftyJSON's JSON.

See: Alamofire-SwiftyJSON

Work with Moya

SwiftyJSON parse data to JSON:

let provider = MoyaProvider<Backend>()
provider.request(.showProducts) { result in
    switch result {
    case let .success(moyaResponse):
        let data = moyaResponse.data
        let json = JSON(data: data) // convert network data to json
        print(json)
    case let .failure(error):
        print("error: \(error)")
    }
}

SwiftyJSON Model Generator

Tools to generate SwiftyJSON Models

alamofire-swiftyjson's People

Contributors

endel avatar jregnauld avatar luketangpl avatar nubek avatar perryprog avatar rnitta avatar rokgregoric avatar rromanchuk avatar thomasdegry avatar trungungtoan-agilityio avatar wongzigii avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alamofire-swiftyjson's Issues

Support for Carthage

I'm not sure if there is support, but when I add to my Cartfile the line github "SwiftyJSON/Alamofire-SwiftyJSON", I get the error:

*** Skipped building Alamofire-SwiftyJSON due to the error:
Dependency "Alamofire-SwiftyJSON" has no shared framework schemes

If you believe this to be an error, please file an issue with the maintainers at https://github.com/SwiftyJSON/Alamofire-SwiftyJSON/issues/new

Push to cocoapods

I see there is a podspec file but Alamofire-SwiftyJSON is not a available on cocoapods.org. It seems to be possible to have swift dependencies on cocoapods using cocoapods 0.36.0.

Could you push it?

'JSON' is not convertible to 'JSON'

I added the files of all the 3 Projects (alamofire, swiftyjson, alamofire-swiftyjson) to my project. When launching the app i get a compile error in:

/Users/ABCDEF/Documents/ios/Stream/Libraries/Alamofire-SwiftyJSON/Alamofire-SwiftyJSON.swift:51:47: 'JSON' is not convertible to 'JSON'

Does someone have any hints how to integrate the projects to a custom project?

Thanks in advance.
Greetings

Adapt to Alamofire 1.3.0

The parameter name for serializer from the response function has change to responseSerializer.

SwiftyJSON @ 11fdc5c doesn't exist

I'm trying to use this repo in CocoaPods but there's an error retrieving the mentioned version of SwiftyJSON. I think it's just matter of pointing to the right tree.

Remove submodules

Use a Cocoapods as dependencies and fetch them for the test Examples project

Please update for Alamofire 3.0

In alamofire 3.0, they using

Response<T.SerializedObject, T.ErrorObject> -> Void

instead of

(request, response, result) -> Void

Installation instruction

For now I just copied swift file into project. Could you add instruction for normal installation or PR to Alamofire, please?

Unable to build using Xcode9

I'm using carthage to pull in Alamofire-SwiftyJSON and when trying to build with Xcode 9 GM, I get the following build error:

*** Building scheme "AlamofireSwiftyJSON" in Alamofire-SwiftyJSON.xcodeproj
*** Building scheme "AWSCore" in AWSiOSSDKv2.xcodeproj
Build Failed
Task failed with exit code 65:
/usr/bin/xcrun xcodebuild -project /Users/troyibm/git/WPA4Auto-iPadApp-ios11/WPAAutoDemo/Carthage/Checkouts/aws-sdk-ios/AWSiOSSDKv2.xcodeproj -scheme AWSCore -configuration Release -derivedDataPath /Users/troyibm/Library/Caches/org.carthage.CarthageKit/DerivedData/9.0_9A235/aws-sdk-ios/40c7d5d60e0b80d70cd1502ef0cf8507f023f8d5 -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES build (launched in /Users/troyibm/git/WPA4Auto-iPadApp-ios11/WPAAutoDemo/Carthage/Checkouts/aws-sdk-ios)

I'm using the following in my Cartfile:

github "Alamofire/Alamofire" ~> 4.5
github "SwiftyJSON/SwiftyJSON"
github "SwiftyJSON/Alamofire-SwiftyJSON" "master"

Getting wrong

New to Swift, but when followed the usage example in readme, still not get correct execution order:

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
            .responseSwiftyJSON { (request, response, json, error) in
    println("first")
}
println("second")

the "second" got printed before "first".

Is there something I missed?

Thanks.

Compile time issue

Hi,

I am getting an error on line 40 with missing parameter for completionHandler.
Subsequent errors follow after correction.

Please review with xcode 7.6 beta and Alamofire 1.3.1 on deployment target 8.4

Regards,

Brian Minnaar

SPM support please

SwiftyJSON and Alamofire both support Swift Package Manager.
So it's useful if this repo support SPM.

Ambiguous use of 'responseSwiftyJSON'

Hello,

after installing Xcode 6.3 the following code

Alamofire .request(.POST, url, parameters: data) .responseSwiftyJSON { (_, _, json, error) in
    if (error != nil) {
        println("Error with registration: \(error?.localizedDescription)")
     } else {
        println("Success!")
    }
}

produces the problem "Ambiguous use of 'responseSwiftyJSON'".

No Such Module SwiftyJSON in AlamofireSwiftyJSON.swift

I have been using Alamofire without issue, and I also have SwiftyJSON working. When I attempt to add this extension, I get an error within AlamofireSwiftyJSON.swift like this:

swiftyjson

I get that if I have included the .swift file in my project, I don't need to have the import SwiftyJSON bit, but if I remove it, I get more errors throughout this same file.

Any idea what I'm doing wrong?

Wrong PLIST entry in version 3.0.0

Inside the info.plist the bundle version string is still set to 2.0.0-beta.1 and not to 3.0.0:

screenshot01

This causes, that you get the following kind of error, when you try to upload an app with this framework to the App Store (or TestFlight):

screenshot02

support JSON as parameter?

Alamofire.request(method: Method, URLString: URLStringConvertible, parameters: JSON String?, encoding: ParameterEncoding)

Can't compile with Xcode 10.2

Xcode 10.2 was released today, which made Swift 5 the latest version, and dropped support for Swift 3. However, this project's Swift version is still set to Swift 3, so this project can't be compiled with Xcode 10.2 or be used with Swift 5 targets

Error!

captura de pantalla 2014-11-01 a las 5 52 43 p m

I have tried to use the library but when I try I get Error .responseSwiftyJSON place, also I have a warring not as removed.
Can you help me?

how to use in XCode 6.1

compile failed

'JSON.Type' does not have a member named 'Null'

                if error != nil {
                    responseJSON = SwiftyJSON.JSON.Null(error)
                } else if object != nil {
                    responseJSON = SwiftyJSON.JSON(object: object!)
                } else {
                    responseJSON = SwiftyJSON.JSON.Null(nil)
                }

Ambigous Error in Swift 1.2

在 Swift 1.2中下面两个方法的签名是等价的:

   public func responseSwiftyJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, JSON, NSError?) -> Void) -> Self 
// VS
    public func responseSwiftyJSON(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, JSON, NSError?) -> Void) -> Self 

Cannot call value of non-function type NSHTTPURLResponse

Hello ! I have installed Alamofire 3.0 and SwiftyJSON 2.3 via CocoaPods and then I have just brough Alamofire-SwiftyJSON manually in my XCode project.

When I try building it I get an error on line 40 in Alamofire-SwiftyJSON.swift yelling at me like the following:

Cannot call value of non-function type NSHTTPURLResponse

Any idea how to fix this ?

The bundle contains disallowed nested bundles.

When submitting ios build with XCode 9.4, Swift 4.1.2 and Carthage I got this error:
Invalid Bundle. The bundle at 'MyApp.app/Frameworks/AlamofireSwiftyJSON.framework' contains disallowed nested bundles. An unknown error occurred.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.