- samplecode.swift Select all
import Foundation
let str1 = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let str2 = "{\"names\": [\"Bob2\", \"Tim2\", \"Tina2\"]};"
for str in [str1, str2] {
let data = str.data(using: String.Encoding.utf8)
// let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // Swift 2
do {
let json = try JSONSerialization.jsonObject(with: data!) as! [String: AnyObject]
// let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) // Swift 2
print(json)
if let names = json["names"] as? [String] {
print(names)
}
} catch let error as NSError {
print(str)
print("Failed to load: \(error.localizedDescription)")
}
}
Sample Code with json from url in swift 3 (Xcode 8 beta 6) with Swift 2 code shown beneath
- samplecode.swift Select all
import Foundation
struct Video {
var name: String
var url: String
}
var musicvideo:[Video]=[]
typealias JSONDictionary = [String: AnyObject]
typealias JSONArray = Array<AnyObject>
let url = Foundation.URL(string: "https://itunes.apple.com/us/rss/topmusicvideos/limit=3/json")
//let url = NSURL(string: "https://itunes.apple.com/us/rss/topmusicvideos/limit=3/json") // Swift 2
do {
let data = try Data(contentsOf: url!)
// let data = NSData(contentsOfURL: url!) // Swift 2
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! JSONDictionary
// .allowFragments - top level object is not Array nor Dictionary.
// let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) // Swift 2
if let feed = json["feed"] as? JSONDictionary,
let entries = feed["entry"] as? JSONArray {
// entries = feed["entry"] as? JSONArray { // Swift 2
//print(entries)
for (index, entry) in entries.enumerated() {
// for (index, entry) in entries.enumerate() { // Swift 2
//print("\(index) is \(entry)")
if let name = entry["im:name"] as? JSONDictionary,
let vName = name["label"] as? String, // SE-0099 XCode 8 beta 4
// vName = name["label"] as? String, // Swift 2
let video = entry["link"] as? JSONArray, // SE-0099 XCode 8 beta 4
// video = entry["link"] as? JSONArray, // Swift 2
let vUrl = video[1] as? JSONDictionary, // SE-0099 XCode 8 beta 4
// vUrl = video[1] as? JSONDictionary, // Swift 2
let vHref = vUrl["attributes"] as? JSONDictionary, // SE-0099 XCode 8 beta 4
// vHref = vUrl["attributes"] as? JSONDictionary, // Swift 2
let vVideoUrl = vHref["href"] as? String // SE-0099 XCode 8 beta 4
// vVideoUrl = vHref["href"] as? String // Swift 2
{
print(vName)
print(vVideoUrl)
musicvideo.append(Video(name: vName, url:vVideoUrl))
}
}
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
let jsonDict = musicvideo.map { return ["name":$0.name, "url":$0.url]}
print(jsonDict)
No comments:
Post a Comment