JSONValue 3.0.2

JSONValue 3.0.2

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布日期最后发布2024年4月
SPM支持 SPM

James RichardJace Conflenti 维护。



JSONValue 3.0.2

JSONValue 是在您的 Swift 应用程序中表示 JSON 数据的最好方法。JSON 中的每个类型都是 JSONValue 枚举中的一个案例,通过使用新的语法和模式匹配,JSONValue 提供了一种干净和健壮的方式来访问数据。

使用方法

解释如何使用 JSONValue 的最佳方式是提供一个示例。使用 JSONValue 有两种方式。您可以使用模式匹配,它内置于 Swift 中以处理枚举,或者您可以使用 value() 方法,该方法将使用 Swift 的错误处理来处理错误情况。为了简洁,我在这里做了很多 API 调用。请不要在生产代码中这样做!

模式匹配

import JSONValue

// Our example string
let JSONDataString = "[\"wat\", 5, {\"foo\": 3.5, \"bar\": null, \"baz\": true}]"

// JSONValue comes with an NSData decoder; we'll use that to convert our string 
// to a JSONValue
let JSONData = JSONDataString.dataUsingEncoding(.utf8)!
let JSONRoot = try! JSONValueJSONDataCoder().decodeJSONValue(JSONData)

// Start by pulling out our root item; JSON will be a [JSONValue], and we can access it
// like any other array.
guard case .array(let JSON) = JSONRoot else {
    return
}

// Lets access the first item in our array, confirming its a String type
guard case .string(let firstItemValue) = JSON[0] else {
    // If this block gets hit, the first item in our array isn't a string.
    // In our case it is so it isn't hit. Using guard this way
    // allows you to fail early when the JSON isn't what you expect
    return
}

// Now we have a local variable called firstItemValue that is a Swift.String 
// containing the value "wat"
print(firstItemValue) // Prints "wat"

// You can also use if instead of guard, if you don't care as much about
// the variable being what you expect it to be.
if case .Int(let secondItemValue) = JSON[1] {
    print(secondItemValue) // Prints 5
}

// Our third item is a dictionary. We'll extract that data out into a regular 
// Swift dictionary of type [String: JSONValue]

// Guard also makes a matched variable available at the scope it was
// called. This allows you to prevent nesting if's if the condition
// is required for subsequent statements. In this use of guard
// i'll place the let before the case; this is typical when
// an enum has more than one associated value.
guard case let .dictionary(thirdItemValue) = JSON[2] else { return }

// Now for some fancy Swift pattern matching. We want our JSONValue.Double's 
// value from thirdItemValue under the "foo" key:
guard case .double(let fooValue)? = thirdItemValue["foo"] else { return }

// Note that our ? in the above example is a use of the new Optional
// pattern matching in Swift 2. It unwraps the dictionary result for
// us.

print(fooValue) // Prints 3.5

// Lets skip over "bar" for now, and grab our "baz"

guard case .bool(let bazValue)? = thirdItemValue["baz"] else { return }

print(bazValue) // Prints true

可空性

在上一个示例中,有一个具有“bar”键的字典项,并且它被设置为 null。JSONValue 有一个名为 Null 的案例,但与它交互不是很方便;它是唯一一个没有相关值的类型,并且期望它存在并不是人们通常会做的事情。为了处理可空值,JSONValue 有一个名为 nullable 的属性。它是一个简单的方法:它返回一个可选的 JSONValue。如果情况是 .Null,则返回 nil,否则返回 self。在我们的上一个示例中,假设“bar”可以返回一个 String,但在这个例子中数据并不存在,因此 API 返回 null。这里是利用它的方式

if case .String(let barValue)? = thirdItemValue["bar"]?.nullable {
    print(barValue) // Would print the string contained in "bar", if it had one.
}

value() 和错误处理

我们将在这里跳过解码,因为它在上面示例中已经介绍了。

// Lets access the first item in our array, confirming its a String type
let firstItemValue: String = try JSON[0].value()

// Now we have a local variable called firstItemValue that is a Swift.String 
// containing the value "wat"
print(firstItemValue) // Prints "wat"

let secondItemValue: Int64 = try JSON[1].value()
print(secondItemValue) // Prints 5


// Our third item is a dictionary. We'll extract that data out into a regular 
// Swift dictionary of type [String: JSONValue]

let thirdItemValue: [String: JSONValue] = try JSON[2].value()

// value() supports working with optionals. If there isn't a value at "foo", or the value
// is .Null, we'll return nil:
let fooValue: Double? = try thirdItemValue["foo"]?.value()

if let unwrapped = fooValue {
    print(unwrapped) // Prints 3.5
}

// You can also unwrap into a non-optional
if let unwrapped: Double = try thirdItemValue["foo"]?.value() {
    print(unwrapped) // Prints 3.5
}

// An example of a nil item:
let watValue: Double? = try thirdItemValue["wat"]?.value()

print(watValue) // Prints nil

自定义解码器

JSONValue 随附一个解码器,即 JSONValueJSONDataCoder。它实现了 JSONValueCoder 协议,该协议定义了处理 JSON数据的最佳实践,例如错误处理和双向编码。JSONValueJSONDataCoder 在底层使用 Foundation 的 NSJSONSerialization 类来保持库的大小,这可能不是您的最佳选择。

如果您想创建自己的 JSONValueCoder,建议查看 JSONValueJSONDataCoder 的实现。当然,如果您愿意,您也可以创建自己的编码器或解码器实现,并像您所希望的那样创建它们。JSONValue 的任何内容都没有绑定到 JSONValueCoder 协议。

联系

我们通常也在 Gitter 聊天室!

贡献

我们很高兴得到您的帮助,使 JSONValue 更好。如果遇到任何问题,请随时

  • 提出一个问题。
  • 分叉项目并提交拉取请求。

许可证

版权所有 © 2015,Weebly。保留所有权利。

以下条件满足时,允许重新分配和使用源代码和二进制代码,是否修改

源代码重新分配必须保留上述版权声明,本条件清单和以下免责声明。二进制形式的重新分配必须复制上述版权声明、本条件清单和以下免责声明在提供的文档或其他材料中。未经事先书面许可,不得使用 Weebly 或其贡献者的姓名来认可或推广由此软件派生的产品。本软件由版权所有者和贡献者提供“按原样”以及任何明示或暗示的保证,包括但不仅限于适销性和针对特定目的的适用性的保证均予以否认。在任何情况下,Weebly,Inc 均不承担任何直接、间接、偶然、特殊、示范性或后果性的损害赔偿责任(包括但不限于替代商品或服务的采购;使用、数据或利润丢失;或业务中断),无论是否因使用本软件引起,即使已告知此类损害赔偿责任的可能性。