RosettaCodeData/Task/JSON/Swift/json.swift

20 lines
536 B
Swift
Raw Permalink Normal View History

2016-12-05 23:44:36 +01:00
import Foundation
let jsonString = "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"
2017-09-23 10:01:46 +02:00
if let jsonData = jsonString.data(using: .utf8) {
if let jsonObject: Any = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) {
print("Dictionary: \(jsonObject)")
}
2016-12-05 23:44:36 +01:00
}
let obj = [
2017-09-23 10:01:46 +02:00
"foo": [1, "Orange"],
"bar": 1
] as [String : Any]
2016-12-05 23:44:36 +01:00
2017-09-23 10:01:46 +02:00
if let objData = try? JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted) {
if let jsonString2 = String(data: objData, encoding: .utf8) {
print("JSON: \(jsonString2)")
}
2016-12-05 23:44:36 +01:00
}