# SwiftyJSON
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com)
SwiftyJSON makes it easy to deal with JSON data in Swift.
Platform | Build Status
---------| --------------|
*OS | [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) |
[Linux](https://github.com/IBM-Swift/SwiftyJSON) | [![Build Status](https://travis-ci.org/IBM-Swift/SwiftyJSON.svg?branch=master)](https://travis-ci.org/IBM-Swift/SwiftyJSON) |
1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good)
2. [Requirements](#requirements)
3. [Integration](#integration)
4. [Usage](#usage)
- [Initialization](#initialization)
- [Subscript](#subscript)
- [Loop](#loop)
- [Error](#error)
- [Optional getter](#optional-getter)
- [Non-optional getter](#non-optional-getter)
- [Setter](#setter)
- [Raw object](#raw-object)
- [Literal convertibles](#literal-convertibles)
- [Merging](#merging)
5. [Work with Alamofire](#work-with-alamofire)
6. [Work with Moya](#work-with-moya)
7. [SwiftyJSON Model Generator](#swiftyjson-model-generator)
> [中文介绍](http://tangplin.github.io/swiftyjson/)
## 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](https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline)).
The code would look like this:
```swift
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:
```swift
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:
```swift
let json = 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.
```swift
let json = 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](http://cocoapods.org/) to install `SwiftyJSON` by adding it to your `Podfile`:
```ruby
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](https://github.com/Carthage/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](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file:
```swift
// 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
```swift
import SwiftyJSON
```
```swift
let json = JSON(data: dataFromNetworking)
```
Or
```swift
let json = JSON(jsonObject)
```
Or
```swift
if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
}
```
#### Subscript
```swift
// Getting a double from a JSON Array
let name = json[0].double
```
```swift
// Getting an array of string from a JSON Array
let arrayNames = json["users"].arrayValue.map {$0["name"].stringValue}
```
```swift
// Getting a string from a JSON Dictionary
let name = json["name"].stringValue
```
```swift
// 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
```
```swift
// With a hard way
let name = json[].string
```
```swift
// With a custom way
let keys:[JSONSubscriptType] = [1,"list",2,"name"]
let name = json[keys].string
```
#### Loop
```swift
// 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*
```swift
// 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.
```swift
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"
}
```
```swift
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"
}
```
```swift
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
```swift
// NSNumber
if let id = json["user"]["favourites_count"].number
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
Web2 App是将您的网站转换为真实的IOS应用程序的最简单方法。此外,我们还提供了强大的功能,如标签,抽屉,内置广告,通知以及轻松的自定义和样式选项。 更容易些 h、.m、.x 第一个应用?没问题.我们提供了一个很好的文档让你开始! 完全可定制 除了我们默认的自定义选项之外。WebToApp的有一个完整的开源代码,这样你就可以自定义和添加你想要的一切。 高级支持 如果您无法在文档或我们的社区常见问题解答中找到答案,我们将提供个人支持。 伟大的定制 选择您最喜欢的主题颜色和联合收割机它与我们的许多布局选项之一。这是我们有史以来最可定制的模板。 标签栏和Darwer 也可以使用选项卡或抽屉将所有网页添加到WebView应用程序。 可隐藏的导航栏 更多的屏幕空间与隐藏的酒吧。这种熟悉的导航模式也可以在Safari中看到。向下滚动隐藏工具栏,向上滚动显示工具栏! 拉取刷新 选择只需轻扫手势即可刷新页面。您还可以使用这种时尚的布局来指示页面加载。 使用OneSignal推送通知 通过OneSignal的推送通知通知您的用户有关新内容,您将获得无限的通知! Admob 在几秒钟内
资源推荐
资源详情
资源评论
收起资源包目录
Web2App for IOS将您的网站转换为真实的IOS应用程序 Webview项目源码IOS (1534个子文件)
pb_decode.c 47KB
pb_encode.c 27KB
pb_common.c 3KB
Assets.car 65KB
CHANGELOG 36KB
style.css 586B
Current 1B
Current 1B
.DS_Store 14KB
.DS_Store 10KB
.DS_Store 6KB
.DS_Store 6KB
.DS_Store 6KB
.DS_Store 6KB
Universal.entitlements 181B
File 0B
equalizer.gif 8KB
GoogleAppMeasurement 31.63MB
GoogleMaps 35.09MB
GoogleMapsBase 38.83MB
GoogleMapsCore 84.11MB
README.GoogleMapsDemos 955B
GoogleMobileAds 86.18MB
oss_licenses_maps.txt.gz 48KB
YTPlayerView.h 28KB
OneSignal.h 24KB
pb.h 23KB
SWRevealViewController.h 23KB
GMSMapView.h 17KB
FBLPromise+Wrap.h 15KB
SDWebImageManager.h 14KB
NSButton+WebCache.h 12KB
UIButton+WebCache.h 11KB
SDWebImageDownloader.h 11KB
OneSignal.h 11KB
SDImageCache.h 11KB
GMSPanoramaView.h 10KB
GULOriginalIMPConvenienceMacros.h 10KB
FBKVOController.h 9KB
UIImageView+WebCache.h 9KB
GMSGeometryUtils.h 9KB
FBLPromise+Retry.h 9KB
GADUnifiedNativeAd.h 8KB
UIView+WebCache.h 7KB
GMSCameraPosition.h 7KB
KILabel.h 7KB
pb_decode.h 6KB
GADMediationAdapter.h 6KB
pb_encode.h 6KB
GADRequest.h 6KB
GADAdSize.h 6KB
GMSMarker.h 6KB
GULLogger.h 6KB
GoogleMobileAds.h 6KB
CJPAdMobHelper.h 5KB
GADMobileAds.h 5KB
GADDynamicHeightSearchRequest.h 5KB
UITableView+FDTemplateLayoutCell.h 5KB
GADBannerView.h 5KB
SDWebImageDownloaderOperation.h 5KB
GADMAdNetworkAdapterProtocol.h 5KB
SDWebImageTransition.h 5KB
GADNativeCustomTemplateAd.h 4KB
GADInterstitial.h 4KB
UIImageView+HighlightedWebCache.h 4KB
GULAppDelegateSwizzler.h 4KB
GADRewardedAd.h 4KB
GADMAdNetworkConnectorProtocol.h 4KB
SDWebImageCoder.h 4KB
SDWebImagePrefetcher.h 4KB
GADMediatedUnifiedNativeAd.h 4KB
GMSMapLayer.h 4KB
GADInAppPurchase.h 4KB
DFPBannerView.h 4KB
GULNetwork.h 4KB
GMSPath.h 4KB
GADNativeExpressAdView.h 4KB
GMSTileLayer.h 4KB
GULLoggerCodes.h 3KB
GMSUISettings.h 3KB
GADMRewardBasedVideoAdNetworkAdapterProtocol.h 3KB
GADMediationAdEventDelegate.h 3KB
GMSCameraUpdate.h 3KB
GMSPolyline.h 3KB
UMPConsentInformation.h 3KB
UMPConsentInformation.h 3KB
GULNetworkConstants.h 3KB
GADRequestConfiguration.h 3KB
SDImageCacheConfig.h 3KB
GULReachabilityChecker.h 3KB
GULNetworkURLSession.h 3KB
GADCustomEventBannerDelegate.h 3KB
GULSwizzler.h 3KB
GADRewardBasedVideoAd.h 3KB
FBLPromise+Any.h 3KB
GULKeychainStorage.h 3KB
GADCustomEventInterstitialDelegate.h 3KB
GADMRewardBasedVideoAdNetworkConnectorProtocol.h 3KB
FBLPromise+Reduce.h 3KB
GMSPanoramaService.h 3KB
共 1534 条
- 1
- 2
- 3
- 4
- 5
- 6
- 16
资源评论
小云同志你好
- 粉丝: 1044
- 资源: 931
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功