Philipp Eibl Philipp Eibl - 6 months ago 13
Swift Question

Special JSON parsing in Swift

I want to build an iOS app for which I need to create an array out of this JSON String that shows only the contents:

[ {"content":"hello"}, {"content":"hi"}, {"content":"how are you?"} ]


The result should look like this:

["hello", "hi", "how are you?"]


How can I do that in Swift?

This is my code in the ViewController.swift file:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let mList = "[{"content":"hello"},{"content":"hi"},{"content":"how are you?"}]"
let data = mList!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

Answer

Your code snippet above won't compile because you need to escape the interior quotes.

This does what you want:

//: Playground - noun: a place where people can play

import UIKit
import Foundation

func arrayFromJSON(jsonString: String) -> [String]
{

    let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
    let array = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as! [[NSObject:AnyObject]]
    return array.map { $0["content"] as! String }
}


let jsonString = "[{\"content\":\"hello\"},{\"content\":\"hi\"},{\"content\":\"how are you?\"}]"

print(arrayFromJSON(jsonString))
Comments