Giter Site home page Giter Site logo

swiftyjson / swiftyjson Goto Github PK

View Code? Open in Web Editor NEW
22.4K 620.0 3.4K 1.1 MB

The better way to deal with JSON data in Swift.

License: MIT License

Swift 98.68% Ruby 0.47% C 0.85%
swiftyjson json swift response request carthage cocoapods json-parsing-library json-parser json-parsing-swift

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

swiftyjson's People

Contributors

aaronpearce avatar bassrock avatar bcapps avatar carloslozano avatar condaatje avatar esbenvb avatar floydpink avatar gsabran avatar hectormatos2011 avatar jeffgukang avatar jobinsjohn avatar johngoren avatar justinmakaila avatar k06a avatar kandelvijaya avatar lbrndnr avatar ldiqual avatar lingoer avatar luketangpl avatar matthew-an avatar mikotozero avatar mokagio avatar otanistudio avatar rastersize avatar saagarjha avatar simonbs avatar skyline75489 avatar thekie avatar wongzigii avatar zhigang1992 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  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

swiftyjson's Issues

NSNull in an array is discarded

In "init (_ rawObject: AnyObject)" the "case let value as NSArray:" try to parse the array value in this line :
let jsonValue = JSONValue(possibleJsonValue)
if jsonValue {
jsonValues.append(jsonValue)
}
but when you have a null in the array no item is added. You have to do a code like that (with a else):
for possibleJsonValue : AnyObject in value {
let jsonValue = JSONValue(possibleJsonValue)
if jsonValue {
jsonValues.append(jsonValue)
} else {
jsonValues.append(JNull)
}
}

NSDictionary to json string to json object

I have a use case where I have an array of dictionaries and I need them as a json object:

var data = [Dictionary<String, String>]()
//append items 
var bytes = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.allZeros, error: nil)
var jsonObj = JSON(NSString(data: bytes!, encoding: NSUTF8StringEncoding)!)

println(jsonObj)
println(jsonObj[0])

The first print statement gives me

[
    {"price":"1.20","city":"Foo","_id":"326105","street":"One"},
    {"price":"1.20","city":"Bar","_id":"326104","street":"Two"}
]

the second

null

but I would expect it to return the first element in the json array. What I am doing wrong?

JSONValue in @objc

When invocating a Swift protocol as Objective-C it fails due to the parameter type JSONValue cannot be represented in Objective-C

@objc protocol MyProtocol
{
    optional func onResultsReceived( results: JSONValue ) <= *** This is going to fail ***
}

Is it possible to declare SwiftyJSON type inside @objc?

Thanks in advance

Looping not working

I am following the example for looping through a JSON response. Creating the initial JSON object works and I am able to fetch properties. When I try to loop through the root Dictionary XCode complains that: Type 'JSON' does not conform to protocol 'SequenceType'

I am using Alamofire to make the HTTP request. Here is my response handler:

request.responseJSON { (request, response, data, error) in
let json = JSON(object: data!)
for (key: String, subJson: JSON) in json {
println(subJson)
}
}

JSON to NSData

Given that I have a JSON object, how do I get a NSData representation, which is suitable for sending over the network, with e.g. a POST request?

No such module "SwiftyJSON"

I'm not sure what is going. Open a new project, drop SwiftyJSON on project tree. Select Copy.
Xcode 6.0.1

Compile and I get "No such Module SwiftyJSON"
Attached screen shot.

screen shot 2014-09-19 at 9 51 18 pm

How to use .count

Hi,
I'm using SwiftyJSON in a project where I'm using

println(boardsJSON["boards"])

to return the following JSON

[
  {
    "idOrganization":null,
    "id":"5325aa22252e6dbe7bc6bf24",
    "pinned":true,
    "name":"Space Tiger",
    "closed":false
  },
  {
    "idOrganization":null,
    "id":"53a6dd5e29abc0630ab317fa",
    "pinned":true,
    "name":"Work Stuff",
    "closed":false
  }
]

I can dive down the tree using something like

println(boardsJSON["boards"][0]["name"])

But if I wanted to iterate over all the names in my JSON how would I get the count of objects in the array?

Trouble getting string representation

Hi,

I am trying to get the string representation of a JSON object.

Given this example

let json:JSON =  ["I":"am", "a":"json"]
println(json.stringValue)

I expect the println output to be ["I":"am", "a":"json"] but it is nil. I have tried with other input data as well, but with the same result every time. the .string method is the same story.

Is the .string and .stringValue method broken, or am I using them wrong?

This is on the xcode6.1 branch by the way.

Option to change NSNull() return value to a real zero value

This is a hugely valuable project you created!

One huge issue I had in my last job was JSON nulls being returned by the web service. For instance, if someone had forgotten to set inventory, I'd get a null instead of zero. So I hacked up a category on NSNull so that I didn't have to test every single value before referencing it. The idea was that in most code, a zero would be just as useful as a null.

You can see others agree by the number of upvotes this answer got on SO: http://stackoverflow.com/a/16610117/1633251

What I am requesting is that you support an option that would result in no nulls being returned, with empty dictionaries, empty arrays, zero length strings, etc being returned instead.

If you want, I'll do the code and submit a pull request, but just tell me exactly how you want the option to work (and the actual string name if you care).

Doesn't work in BETA 6

if i get a NSData (ex: load data from a file) when i pass it to JSONValue(var)
it always says that it's an invalid json object, which is not the case.

Separate implementations of protocols

@lingoer thanks for the push access!
I've added more tests and cleaned the code a little. I'll submit new issues and if they are minor enchacements/ bugs - fix the in place, otherwise discuss with you.

I think it's cool idea to have each protocol to be implemented in it's own extension - the code becomes more readable.

Error: use of unresolved identifier dataFromNetworking

Hii,

Ik have a question :) what do i wrong here? i get the error:

"use of unresolved identifier dataFromNetworking"

This is my code

Alamofire.request(.GET, "http://www.pasveer.nl/api/get_posts")
.responseJSON { (_, _, JSON, _) in

    let json = JSON(data: dataFromNetworking)
    if let userName = json[0]["user"]["name"].string{
        println(userName)
    else{
        //something else
    }
}

What am i doing wrong?

Updating a json

Hi, is there a way to update a JSON object? e.g

let json = JSON(data: dataFromNetworking)
json[0]["user"]["name"] = "new user name"

Issue Parsing Json from .Net json formatter

Note: This is a specific problem when receiving HttpRequest Json data that is being formatted/Sent By .Net Web App into our iOS Apps.

  • I was able to fix this locally, But at least it might be something that can be fixed in source code and it won't affect the result if the original json data is already in correct format.

So the problem is the format of .Net Json Formatter won't be the same when being read by the SwftyJson library since .Net has this special characters that .Net reads fine through them because IT knows them but Swift or Xcode don't recognize so it considers them as wrong data.

The characters in question are the following:

  • the " \ " (Backslash)
  • the " " (whitespace)
  • the " " " (double quotes) Opening and Closing one only.

See in .Net, if you don't know already, requires the ' " ' to be able to create the correct JSon format. However when written in .Net and trying to parse it on Xcode is a problem because it sends NOT ONLY the double quotes but it sends the complete statement as " " " Which becomes a problem and crashes the SwiftyJson and well any other json in Xcode because the backslash becomes part of the unacceptable format.

Also .Net is so friendly with the whitespaces and leaves them there making in very few cases errors.

So I fixed it by Reading the NSData from the Httprequest like so:

  var jsonstring: String = NSString(data: self.data as NSData,encoding: UInt())

next did my string replacement with the following Framework Method:

  jsonstring.stringByReplacingOccurrencesOfString("\\", withString:"", options:NSStringCompareOptions.LiteralSearch, range: nil)

//Do the same for the white spaces.

and last recreate the NSData from the JsonString already parsed and patched:

  var parseData: NSData? = (jsonstring as       NSString).dataUsingEncoding(NSUTF16StringEncoding)//NSUTF8StringEncoding

You are done. Now use JsonValue like you normally would and it will all be perfect.

JSON keep null

I have this this code:

var answers:JSON = JSON.nullJSON
answers["32"].string = answerFirstQuestion.text
answers["42"].string = answerSecondQuestion.text
answers["45"].string = answerThirdQuestion.text
print(answers)

var json:JSON = JSON.nullJSON
json["id"].string = identifier
json["resp"] = answers
println(json)

When I print both json these are null.

Array index out of range

    switch json["val"]{
    case .JString(let sval):
        desLabel.text = sval
    case .JNumber(let ival):
        desLabel.text = ival.stringValue
    case .JArray(let jval):
        if let jname = jval[0]["name"].string{  //fatal error: Array index out of range
            desLabel.text = jname
        }

32bit test failures

Test failures on 32bit. When using the 4S simulator I get a could of test failures including this line:
XCTAssertEqual(JSON(2147483648).description,"2147483648")

Not sure that this can be resolved without forcing it to use Int64's but that will require annoying casts in other places.

Compilation errors

Hi there,

I'm importing SwiftyJSON.swift into my project, but the compiler is flagging up 11 errors - mostly 'Type 'JSON' does not conform to protocol'' for the various LiteralConvertible protocols, and RawRepresentable.

I'm also getting a couple of errors on the line public init?(rawValue: AnyObject) { - 'Expected '(' for initializer parameters' and 'Expected declaration'.

JNumber should be Number not double

From my point of view, it's really annoying that all values are encoded and decoded as double, in some cases this behaviour might be even buggy.
I propose to let caller side decide how to unwrap returned Number - as Double, Int, whatever

iOS 8.1 compatability

Hey there,

I just updated Xcode for iOS 8.1 and this whole library just went BOOM. Just FYI.

Code does not compile in iOS 8 Beta 3.

The following line is returning an error:
if let breadcrumb = userInfo["JSONErrorBreadCrumbKey"] as? String{

Error:
'String' is not a subtype of '(NSObject, AnyObject)'

SourcekitService Terminated Issue

I just forked your project. I used your code in my project

When i open my project with your file(SwiftyJSON.swift) in my Xcode6 Beta it gives me a error "Source Kit Service Terminated Editor functionality temporarily limited"

This causes my whole project syntax highlighting and code completion gone

Anyhow i will also try to solve this. But wanted to raise this as a issue.

Can't use SwiftyJSON as part of a public API within a framework

I've got a framework where I have methods that take a JSONValue object like so:

    public init(json: JSONValue) {
        self.id = json["id"].integer!

        // some other code
    }

I need the class that contains this initializer to be within a framework in order to be able to use Live View functionality introduced with XCode 6. But as everything in SwiftyJSON is implicitly set to internal access control level I receive the following error:
Initializer cannot be declared public because its parameter uses an internal type

Fails to compile on Beta2

CompileSwift normal i386 com.apple.xcode.tools.swift.compiler
    cd /Users/lebedzeu/src/git/SwiftyJSON/Example
    export PATH="/Applications/Xcode6-Beta2.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode6-Beta2.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -target i386-apple-ios8.0 -module-name Example -O0 -sdk /Applications/Xcode6-Beta2.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk -g -module-cache-path /Users/lebedzeu/Library/Developer/Xcode/DerivedData/ModuleCache -I /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Products/Debug-iphonesimulator -F /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Products/Debug-iphonesimulator -c -j4 /Users/lebedzeu/src/git/SwiftyJSON/Example/Example/ViewController.swift /Users/lebedzeu/src/git/SwiftyJSON/SwiftyJSON/SwiftJSON.swift /Users/lebedzeu/src/git/SwiftyJSON/Example/Example/AppDelegate.swift -output-file-map /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Objects-normal/i386/Example-OutputFileMap.json -serialize-diagnostics -emit-dependencies -emit-module -emit-module-path /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Objects-normal/i386/Example.swiftmodule -Xcc -iquote -Xcc /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Example-generated-files.hmap -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Example-own-target-headers.hmap -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Example-all-target-headers.hmap -Xcc -iquote -Xcc /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Example-project-headers.hmap -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Products/Debug-iphonesimulator/include -Xcc -I/Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/DerivedSources/i386 -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/DerivedSources -Xcc -DDEBUG=1 -emit-objc-header -emit-objc-header-path /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Objects-normal/i386/Example-Swift.h

0  swift                    0x000000010352de08 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x000000010352e2f4 SignalHandler(int) + 452
2  libsystem_platform.dylib 0x00007fff82c3d5aa _sigtramp + 26
3  swift                    0x00000001034ee7af llvm::FoldingSetImpl::FindNodeOrInsertPos(llvm::FoldingSetNodeID const&, void*&) + 175
4  swift                    0x000000010295cdc9 swift::irgen::emitOpaqueExistentialContainerUpcast(swift::irgen::IRGenFunction&, swift::irgen::Address, swift::SILType, swift::irgen::Address, swift::SILType, bool) + 169
5  swift                    0x000000010299ba8e swift::SILVisitor<(anonymous namespace)::IRGenSILFunction, void>::visit(swift::ValueBase*) + 35406
6  swift                    0x0000000102992846 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 8678
7  swift                    0x0000000102913cd8 swift::irgen::IRGenModule::emitGlobalTopLevel() + 184
8  swift                    0x000000010297fcc3 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1859
9  swift                    0x0000000102980613 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
10 swift                    0x00000001028f295a frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 4842
11 swift                    0x00000001028f165d main + 1533
12 libdyld.dylib            0x00007fff869765fd start + 1
13 libdyld.dylib            0x0000000000000036 start + 2036898362
Stack dump:
0.  Program arguments: /Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c /Users/lebedzeu/src/git/SwiftyJSON/Example/Example/ViewController.swift -primary-file /Users/lebedzeu/src/git/SwiftyJSON/SwiftyJSON/SwiftJSON.swift /Users/lebedzeu/src/git/SwiftyJSON/Example/Example/AppDelegate.swift -enable-objc-attr-requires-objc-module -target i386-apple-ios8.0 -module-name Example -sdk /Applications/Xcode6-Beta2.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk -I /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Products/Debug-iphonesimulator -F /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Products/Debug-iphonesimulator -g -module-cache-path /Users/lebedzeu/Library/Developer/Xcode/DerivedData/ModuleCache -Xcc -iquote -Xcc /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Example-generated-files.hmap -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Example-own-target-headers.hmap -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Example-all-target-headers.hmap -Xcc -iquote -Xcc /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Example-project-headers.hmap -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Products/Debug-iphonesimulator/include -Xcc -I/Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/DerivedSources/i386 -Xcc -I/Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/DerivedSources -Xcc -DDEBUG=1 -emit-module-doc-path /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Objects-normal/i386/SwiftJSON~partial.swiftdoc -O0 -emit-module-path /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Objects-normal/i386/SwiftJSON~partial.swiftmodule -serialize-diagnostics-path /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Objects-normal/i386/SwiftJSON.dia -emit-dependencies-path /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Objects-normal/i386/SwiftJSON.d -o /Users/lebedzeu/Library/Developer/Xcode/DerivedData/Example-axvjsxtsdwewgkedabcaclklosug/Build/Intermediates/Example.build/Debug-iphonesimulator/Example.build/Objects-normal/i386/SwiftJSON.o 
1.  While emitting IR SIL function @_TFO7Example9JSONValueCfMS0_FPSs9AnyObject_S0_ for 'init' at /Users/lebedzeu/src/git/SwiftyJSON/SwiftyJSON/SwiftJSON.swift:134:5
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254

Type [SubscriptType] Does not conform to protocol 'StringLiteralConvertible'

I think this could be related to other issues reported before, but this has been frustrating me since yesterday and it didn't solve, even after update to the latest version.

I don't understand why it is firing inside a specific point, and I have also other lines where I do the same and they are not firing anything.

    searchReq = Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/place/details/json", parameters:params)
        .responseSwiftyJSON({ (req:NSURLRequest, response:NSHTTPURLResponse?, data:SwiftyJSON.JSON, error:NSError?) -> Void in

            UIApplication.sharedApplication().networkActivityIndicatorVisible = false

            if data != nil && data["status"] == "OK" {

                println(data["result"]["formatted_address"])
                if data["result"]["geometry"]["location"].dictionary != nil {

                    // This is the line that fires error
                    let coords:CLLocationCoordinate2D = CLLocationCoordinate2DMake(data["result"]["geometry"]["location"]["lat"],
                                                                                   data["result"]["geometry"]["location"]["lng"])
                    self.addPinToLocation(coords, title:self.selectedLocationHint?["description"] as String!, subtitle:"", focus:true)
                }
            }
        })

captura de pantalla 2014-10-22 a las 9 42 06

Can't access property

This is my json:
{"error":{"title":"Cannot login","message":"Username is required"}}

This is my code, the last println is never executed:
let json = JSONValue(response)
println(response)
if let userName = json["error"]["title"].string{
println(userName)
}

Couldn't Compile and Run

I'm having challenges with JSONSerialization in swift, so downloaded this to try. It says source kit terminated famous XCode 6 message if I try to compile and run.

Updating Dictionary

What is the procedure to add a key value pair to a dictionary that is implemented using JSONValue?

Examples with AFHTTPSessionManager?

Unfortunately my current project uses AFHTTPSessionManager in AFNetworking2, so I can't use Alamofire. Does SwiftyJSON still work with AFHTTPSessionManager? If so, how can I call JSON from AFHTTPSessionManager? I don't see NSData exposed in success block.

I have the following block of code, how do I convert responseObject, which can be downcasted to NSDictionary, to a JSON object as defined in SwiftyJSON? The code below doesn't work.

            let task:NSURLSessionDataTask = AFHTTPSessionManager.GET(
                url,
                parameters: params,
                success: { (task: NSURLSessionDataTask!, responseObject: AnyObject!) in

                    dispatch_async(dispatch_get_main_queue(), {

                        // How do I convert responseObject, which can be downcasted to NSDictionary to a JSON object?
                        let data = JSON(data: responseObject)
                        completion(task: task, response: data as JSON!, error: nil)
                    })
                },
                failure: { (task: NSURLSessionDataTask!, error: NSError!) in
                    dispatch_async(dispatch_get_main_queue(), {
                        completion(task: task, response: nil, error: error)
                    })
                }
            )

Can't set value

What I'm trying to do:

var JSONObject = JSON(data: data)
JSONObject["test"] = JSON("test")

It gives me the following error on the second line: " '@lvalue $T7' is not identical to 'JSON' "

What am I doing wrong?

Length of an array

This is some good stuff! For the life of me ... I cannot see where I can grab the length of an array??

Iterating through a JSON response

I get a JSON response from a web service which looks like this.

{
  "1":"Rooms",
  "2":"Kitchen",
  "3":"Bed1",
  "4":"Bed2",
  "5":"Bed3",
  "6":"Master",
  "7":"Breakfast",
  "8":"Bath1",
  "9":"Bath2",
  "10":"Living"
}

As you can see it's a list of rooms. Each room has a number and a name. I have created a model class called Room with two properties for ID and Name.

Here is the method I call the web service to get the response.

public func getRooms(completionHandler: (response: [Room]?, error: NSError?) -> Void) {
    let response = {(response: NSHTTPURLResponse!, data: HTTPHandler.Data!, error: NSError!) -> Void in
        let json = JSONValue(data)
        println(json["rooms"])

    }
    let httphandler = HTTPHandler.get("http://webservie.com/rooms", response: response)
}

I want to return an array of Room class objects. I get the JSON response to the json constant properly. How can I iterate through it and collect the objects into an array? I tried to do a for in loop on it but apparently its not possible.

Can someone please help me out?

Thank you.

Problem converting JSONValue to AnyObject

I am trying to achieve this:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let place = places![indexPath.row]
    self.performSegueWithIdentifier("segue_order", sender: place)
}

I am getting error:

Type 'JSONValue' does not conform to protocol 'AnyObject'

Remove prefix from enum values?

```case JNumber(Double)
case JString(String)
case JBool(Bool)
case JNull
case JArray(Array<JSONValue>)
case JObject(Dictionary<String,JSONValue>)
case JInvalid```

Now we have all the enum values prefixed with J. It's unnecessary since collisions are impossible with swift enums.

String parsing

Cool library!

Having trouble getting the right output from string input:

var json = JSONValue("{\"a\":\"b\"}") // (Enum Value)
json == JSONValue.JInvalid // false
json["a"].string // nil

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.