通过提供类似 JS-的 API,使在 Swift 中使用 JSON 变得直观

DirectJSON

安装和使用

一个 Swift 包,它使您能够直观地使用 JSON,就像在 JavaScript 中一样。只需使用点即可访问 JSON 结构,如下所示:

let brand : String? = theCarsOf2023.json.ev.popular[0].brand

没什么可学的

DirectJSON 将扩展字符串类型和 您将能够通过以下方式访问 JSON 字符串的任何部分 .json 属性。它使用 @dynamicMemberLookup 来解码您要访问的路径。

您可以使用任何有效的 JSON 字符串。让我们看一下以下内容:

// This is our JSON String 
let countryData = "{\"name\" : \"Türkiye\", \"facts\" : {\"population\" : 85000000, \"GDP\" : 815} , \"tags\" : [\"Europe\", \"Asia\", \"Middle East\"] }"
                  
            
//Access a property value
let name : String? = countryData.json.name
            
//Access a property value as any Codable Swift Type
let population : Int? = countryData.json.facts.population
            
//Access a property using a custom Decoder
let population : Int? = countryData.json.facts.population.jsonDecode(myCustomDecoder)
            
//You can convert the JSON String directly to any Codable Swift Type
let country : Country? = countryData.json.jsonDecode()
            
//Access array values using index
let firstTag : String? = countryData.json.tags[0]

安装和使用

DirectJSON 使用 Swift 包管理器,支持所有平台,像任何其他包一样将其添加到您的项目中。

使用 Xcode:

在 Xcode 中单击 ->。FileAdd Packages...

在右上角有一个文本框,上面写着.Search or Enter Package URL

复制并粘贴其中。等待包数据加载完毕,然后单击按钮。按照说明完成包的添加。https://github.com/mrtksn/DirectJSON.gitAdd Package

Using Package.swift:

Alternatively, you can add the package by editing your Package.swift file. On your dependencies, add the URL as shown here.

// swift-tools-version:4.0
import PackageDescription

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

Then run command.swift build

How to use:

Once you add the package, you can simply include the package and start using it like this:

import DirectJSON

// ready to use. Just add .json to any String to access the functions

let stars : Int? = "{\"stars\" : 10}".json.stars
// result: Optional(10)

Comes with a few tools

The following API can be useful to streamline yourworkflow:

Turn any Swift object(that conforms to Codable) into a String

 let car = try? JSON.encode(someCarObject)
 // result: {"brand" : "Tesla", "type" : "ev"}

Get a part of the JSON String as a String

let evs = theCarsOf2023.json.ev.stringify()
// result: {"popular" : [car1, car2 ...], "topSpeed" : [car9, car3 ...]}

Cookbook

Swift is a Typed language, JavaScript and consequently JSON are not. This creates hardships when converting from JavaScript into Swift.

Here we will list ideas on how to solve some common issues like this.

Working with Arrays containing multiple types:

let jobDescription = "{\"title\" : \"developer\", \"tags\" : [\"php\", \"js\", \"swift\", 2022, 2023]}"
                
var years = [Int]()
                
switch jobDescription.json.tags{
    case .arrayType(let arr):
        years = arr.compactMap({ $0.getValue() as? Double }).map({Int($0)})
    default:
        break
}
print("years:", years)
//result: years: [2022, 2023]

Limitations

At this time fragmanted JSON is not supported. This is because Apple’s JSONDecode also does not support JSON fragments.

GitHub

点击跳转