Philipp Eibl Philipp Eibl - 2 years ago 97
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() {

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


override func didReceiveMemoryWarning() {

Answer Source

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 { $0["content"] as! String }

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download