带有值类型的JSONSerialization

时间:2016-07-30 06:15:14

标签: json swift swift3

我想使用Foundation的JSONSerialization.data(withJSONObject obj: AnyObject, options opt: WritingOptions = []) throws -> Data。但是,我无法弄清楚如何将我的值类型转换为适合该方法的引用类型。

例如,尝试序列化一个简单的String数组失败,因为该方法需要引用类型,而不是值类型:

root@1c6c66df21cf:/tmp# swift
Welcome to Swift version 3.0 (swift-3.0-PREVIEW-3). Type :help for assistance.
  1> import Foundation
  2> JSONSerialization.data( withJSONObject: [String]() )
error: repl.swift:2:48: error: argument type '[String]' does not conform to expected type 'AnyObject'
JSONSerialization.data( withJSONObject: [String]() )

投射不起作用:

root@1c6c66df21cf:/tmp# swift
Welcome to Swift version 3.0 (swift-3.0-PREVIEW-3). Type :help for assistance.
  1> import Foundation
  2> let value = [String]()
value: [String] = 0 values
  3> let reference = value as! NSArray
reference: Foundation.NSArray = <extracting data from value failed>

Execution interrupted. Enter code to recover and continue.
Enter LLDB commands to investigate (type :help for assistance.)

我还尝试按照unit tests中针对该版本核心基金会的示例进行操作:

root@1c6c66df21cf:/tmp# swift
Welcome to Swift version 3.0 (swift-3.0-PREVIEW-3). Type :help for assistance.
  1> import Foundation
  2> let value = [String]()
value: [String] = 0 values
  3> let reference = value.bridge()
reference: Foundation.NSArray = <extracting data from value failed>

error: Couldn't lookup symbols:
  (extension in Foundation):Swift.Array.bridge () -> Foundation.NSArray

供参考的系统信息:

root@1c6c66df21cf:/tmp# uname -a
Linux 1c6c66df21cf 4.4.12-boot2docker #1 SMP Wed Jun 1 22:45:59 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
root@1c6c66df21cf:/tmp# swift --version
Swift version 3.0 (swift-3.0-PREVIEW-3)
Target: x86_64-unknown-linux-gnu

1 个答案:

答案 0 :(得分:0)

使用.bridge()是正确的方法。该错误特定于REPL。编译整个文件时不会发生这种情况:

root@1c6c66df21cf:/tmp# cat test.swift 
import Foundation

let value = ["string"]
let reference = value.bridge()
let jsonData = try! JSONSerialization.data(withJSONObject: reference)
print(String(data: jsonData, encoding: .utf8)!)
root@1c6c66df21cf:/tmp# swift test.swift
["string"]
root@1c6c66df21cf:/tmp# swiftc -o test test.swift 
root@1c6c66df21cf:/tmp# ./test
["string"]